Posted on

Description

Submission

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() < 2) return 0;
        vector<int> stk;
        stk.push_back(prices[0]);
        int maxVal = 0;

        for(int i = 1; i < prices.size(); ++i) {
            while(!stk.empty() && prices[i] < stk.back()) {
                maxVal = max(maxVal, stk.back() - stk[0]);
                stk.pop_back();
            }
            stk.push_back(prices[i]);
        }
        if(!stk.empty()) {
            maxVal = max(stk.back() - stk[0], maxVal);
        }
        return maxVal;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *