【LeetCode】121. Best Time to Buy and Sell Stock


Best Time to Buy and Sell Stock

 

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

記ret為收益(賣出-買入)

關鍵點就在於,隨着prices的遍歷,怎樣更新ret?

1、如果當前遇到的元素比curMin小,就重新更新curMin

2、計算prices[i]與curMin的差值,並(可能需要)更新ret

上述順序不可變,不然會產生收益為負的情況。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int m = prices.size();
        if(m == 0)
            return 0;
            
        int curMin = prices[0];
        int ret = 0;
        for(int i = 1; i < m; i ++)
        {
            curMin = min(curMin, prices[i]);
            ret = max(ret, prices[i]-curMin);
        }
        return ret;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM