您的位置:首页 > 其它

LeetCode题解:122. Best Time to Buy and Sell Stock II

2016-04-11 23:38 260 查看

题目链接:

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).

中文解释:

给定一个数组,来存放每一天股票的价格。要求设计一个算法来寻求最大收益,交易次数不限,可以多次买卖,但是不能在同一时间内进行多次交易,而且在卖股票前得保证已经买了股票。

题目解释:

这个题跟121题(我的上一篇博客)算是一个系列的,都是求最优解的,121题要求只能买卖一次,但是本题目不限次数,这样两个题目就有差距了,只能买卖一次的话,我们必须来最低点买入股票,然后再在最高点卖出股票,这样才能获得最高收益。改为能够多次买卖 以后就不一样了,我们不必在乎最低最高点了,我们在乎的每两天之间的差距,只要是涨了我们就要卖掉去换取利益,换句话说我们要积累每一次涨钱的收益。

到这我们其实就可以想到解题的思路了:贪心!,遍历整个数组,后一天比前一天贵的都是我们赚的钱,比如:1 2 3 2 3 2 ,那么我们的收益为: 第二天和第一天之差、第三天和第二天之差、第五天和第四天之差,和为3.

解题方案:

判断后一天比前一天价格高的情况,然后累加他们之间的差值。这个差值之和就是我们的最高收益

AC代码:

下面来看具体的AC代码:

int maxProfit(int* prices, int pricesSize)
{

//  bool flag = false;
int sum = 0;

for(int i = 1; i < pricesSize; ++i)
{
if(prices[i] > prices[i-1])
{
sum += prices[i] - prices[i-1];
}
}
return sum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法