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。代码如下:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 int min = 0; 4 int sump = 0; 5 int mp = 0; 6 7 for (int i = 1; i < prices.length; i++) { 8 if (prices[i] < prices[i-1]){ 9 sump = sump + mp; 10 min = i; 11 mp = 0; 12 } 13 else 14 mp = prices[i] - prices[min]; 15 } 16 17 return sump + mp; 18 } 19 }
其实更加简单直观的代码如下:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 int total = 0; 4 for(int i = 0; i < prices.length-1; i++){ 5 if(prices[i+1] > prices[i]) total += prices[i+1] - prices[i]; 6 } 7 return total; 8 } 9 }
最后要把所有递增序列中的最大值和最小值的差值加起来,其实这个过程和上述代码的描述是相同的。