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

【思路】

相比较上一个题目,这个题目对交易放松了限制,可以做多笔交易,但是在进行下一笔交易之前必须先完成上一笔交易,而且相同交易只能做一次。我的思路是:如果价格在未来上涨,那么我就在当前买入。如果价格在未来下跌,我就在当前卖出。这样的结果就是把数组划分成了一段段的递增序列,在序列的最开始买入,最后卖出。举个例子:[2,1,25,4,5,6,7,2,4,5,1,5]。数组被划分成了5个递增序列,在第一个序列利润为0,第二个序列利润为24,第三个为3,第四个为3,第五个为4.总的利润是34。代码如下:

 public class Solution {
public int maxProfit(int[] prices) {
int min = 0;
int sump = 0;
int mp = 0; for (int i = 1; i < prices.length; i++) {
if (prices[i] < prices[i-1]){
sump = sump + mp;
min = i;
mp = 0;
}
else
mp = prices[i] - prices[min];
} return sump + mp;
}
}

其实更加简单直观的代码如下:

 public class Solution {
public int maxProfit(int[] prices) {
int total = 0;
for(int i = 0; i < prices.length-1; i++){
if(prices[i+1] > prices[i]) total += prices[i+1] - prices[i];
}
return total;
}
}

最后要把所有递增序列中的最大值和最小值的差值加起来,其实这个过程和上述代码的描述是相同的。

上一篇:Asp.net默认配置下,Session莫名丢失的原因及解决


下一篇:Flask基础(3):session、flash、特殊装饰器、蓝图、路由正则匹配、上下文管理 & flask-session