leetcode122题解

leetcode 122. Best Time to Buy and Sell Stock II

题目

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题目意思就是:给定一个数组,第i个值代表的就是第i天的股票价格。在整个周期里面,可以做多次买入或卖出操作,但要求在买入之前,要先卖出当前股票。
看到这道题时有点昏,因为没给example,描述也不是很清晰,这里给几个例子,方便理解。
[1,2,3] 输出:2 [2,1] 输出:0

解题思路

这道题看到之后,我们先分析一个具体的输入——输入:[1,2,3,4]
显然,第一天买入,最后一天卖出,收益最大为3.但考虑这样一种操作,遇到高的我就卖出,并买入。第一天买入,第二天卖出加买入……这样得到的结果也是3。
这其实就是一种贪心算法,下面是两种思路,核心都和刚刚说的类似。
代码1:循环该数组,若发现当前的值大于买入价格,则说明此时就有利润了,卖出并将当前值设为买入价格;若发现当前值小于买入价格,则把当前值设为最小买入价格。
代码2:leetcode上的大神的思路,就是比较相邻两值,后者比前者大就说明有利润,累加进总利润即可

AC代码如下

代码1:

//局部最优之和等于最大利润
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0)return 0;
int sumprofit=0;
int minbuyprice=prices[0];
for(int i=1;i<prices.size();i++){
    if(prices[i]>minbuyprice)
        sumprofit+=prices[i]-minbuyprice;
    minbuyprice=prices[i];
}

return sumprofit;
}
};   

代码2:

 class Solution {
public:
int maxProfit(vector<int>& prices) {
int sumprofit=0;
for(int i=1;i<prices.size();i++){
 sumprofit+=max(prices[i]-prices[i-1],0);   
}
return sumprofit;
}
};

总结

leetcode上easy难度,也是Best Time to Buy and Sell Stock这个系列里面的第二题。
关于贪心算法,在csdn上看到一篇不错的文章。

http://blog.csdn.net/qq_32400847/article/details/51336300

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值