美文网首页Leetcode/Java学习笔记
121. Best Time to Buy and Sell S

121. Best Time to Buy and Sell S

作者: 萧瑟空间 | 来源:发表于2018-09-13 07:26 被阅读0次

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
解法:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2){
            return 0;
        }
        int maxprofit = 0;
        int minprice = prices[0];
        int temp;
        for(int ele: prices){
            temp = ele - minprice;
            if(temp > maxprofit){
                maxprofit = temp;
            }
            if(ele < minprice){
                minprice = ele;
            }
        }
        return maxprofit;
    }
}

第一次做觉得理所当然的方法第二次居然不敢确定这样的做法是不是准确:
有两点值得指出的是:

  • maxprofit可以将目前最好的结果保留下来
  • 碰到当前price低于minprice的时候敢直接将minprice替换为当前price的理由为:
    • 被替换掉的minprice的最优解如果存在则已经被存储在maxprofit中
    • 假如最适合被替换的minprice的卖出价在后面且当前price低于minprice,则当前价格做买入价会有更高的profit

相关文章

网友评论

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

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