2023年1月10日 星期二

121. Best Time to Buy and Sell Stock

解題思路

從後面往前面看,找未來幾天最高價跟現在的價錢比,是不是值得賣出。

ps. 看了其他人的作法才發現我想的倒過來了,但想法正確就好 :D

程式碼

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int currentMax = prices[prices.size() - 1];
        int diffMax = 0;
        for(int i=prices.size() - 1; i>=0; i--)
        {
            if((currentMax - prices[i]) > diffMax)
                diffMax = currentMax - prices[i];
            if(prices[i] > currentMax)
                currentMax = prices[i];
        }
        return diffMax;
    }
};

沒有留言:

張貼留言