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

 


题目标签:Array, Greedy

  这次的题目可以允许我们多次买卖,而 #121题 只允许我们买卖一次。

  回来更新一下解题思路,觉得之前的思路有一点繁琐,现在这个更简单明了。

 

  如何找到最大收益呢,我们可以把数字想象成对应高度的柱状图,当一整段array里,怎么才是最大收益呢?

  就是把所有上升区间里的 最大值(最后一个) 减去 最小值(第一个) 加在一起,就是最大收益值了。

  当我们遇到一个下降的数字,那么此时就是需要把之前的上升区间的profit 值加入maxProfit里的时候了。

  如果一直都是下降区间的话? 每次我们遇到一个下降数字,会把 前面一个数字end-1  减去 start 加入maxProfit,然后在更新start = end。

    所以遇到下降数字的时候,其实就是利用 一个数字减去自己,把0 加入maxProfit,不会影响答案。

  在遇到下降数字时候,start 和 end 不会分开;只有在上升区间里,start 和 end 才会分开,产生一个区间。

 

 

Java Solution:

Runtime beats 52.20% 

完成日期:10/04/2017

关键词:Array, Greedy

关键点:找到所有的ascending range 把它们的profit 累加。

 1 class Solution 
 2 {
 3     public int maxProfit(int[] prices) 
 4     {
 5         if(prices == null || prices.length == 0)
 6             return 0;
 7             
 8         int maxProfit = 0;
 9         int start = 0;
10         int end = 1;
11         
12         while(end < prices.length) // iterate prices array
13         {
14             if(prices[end-1] > prices[end]) // if find any descending number
15             {
16                 maxProfit += (prices[end-1] - prices[start]); // add the previous ascending profit
17                 start = end; // update start pointer from this descending number
18             }
19             
20             end++;
21         }
22         
23         // take care the last part
24         maxProfit += (prices[end-1] - prices[start]);
25         
26         return maxProfit;
27     }
28 }

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

 

posted @ 2017-08-29 06:55  Jimmy_Cheng  阅读(151)  评论(0编辑  收藏  举报