C++ O(N) Time O(N) Space Using Stack


  • 0
    M
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int maxp = 0;
            vector<int> st;
            for (int p: prices) {
                while (!st.empty() && st.back() >= p) st.pop_back();
                st.push_back(p);
                maxp = max(maxp, st.back() - st.front());
            }
            return maxp;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.