美文网首页
121 Best Time to Buy and Sell S

121 Best Time to Buy and Sell S

作者: Mree111 | 来源:发表于2019-04-19 23:34 被阅读0次

Find the range of the stock price which follow the time order
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Solution

Time O(N)
Space O(1)
难点是峰值有可能会对其造成干扰,可能开始出现的max峰值并不能达到profit最大值,找最后出现的最小值可能也不能。因此在one pass的时候可以一边记录当前最小,一边纪录profit,因为在找peak的时候min越小越好。
方法即使用One-pass的方式,始终记录当前遇到的最小值

class Solution {
    public int maxProfit(int[] prices) {
        int min,profit,max_profit;
        min=Integer.MAX_VALUE;
        max_profit=0;
        for(int i=0;i<prices.length;i++){
            if(prices[i]<min){
                min=prices[i]; // guarantee the smallest val which own the order
            }
            else{
                profit=prices[i]-min;
                if(max_profit<profit)
                    max_profit=profit;
            }
        }
    return max_profit;       
    }
}```

相关文章

网友评论

      本文标题:121 Best Time to Buy and Sell S

      本文链接:https://www.haomeiwen.com/subject/aucfgqtx.html