Short 8ms C++ solution with concise explanation

  • 2

    Given that we sell on a day i, the best time to buy would have been the minimum value seen before day i (the running min rmin). The profit would then be a[i] - rmin. Hence we maximize this difference over all values of i (with a running max mp) to get the result.

    class Solution {
        int maxProfit(vector<int>& prices) {
            if (prices.size() == 0) { return 0; }
            int rmin = numeric_limits<int>::max(), mp = numeric_limits<int>::min();
            for (int p : prices) {
                rmin = min(rmin, p);
                mp = max(mp, p - rmin);
            return mp;

Log in to reply

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