10 lines of c++ code / 13 ms with Explaination


  • 0
    P
    class Solution {
    public:
        int maxProfit(vector<int> &a) {
            int profit = 0;
            int bot = 0;
            for (int i = 1; i < a.size(); ++i) {
                // LOGIC : if we find a new low, then update low
                // if we find that the number gives a better profit 
                // and is after the bottom, then update profit
                if (a[bot] > a[i]) {
                    bot = i;
                } else if (i > bot && a[i]-a[bot] > profit) {
                    profit = a[i]-a[bot];
                }
            }
            return profit;
        }
    };

  • 0
    H

    It is not necessary to check if "i > bot".


Log in to reply
 

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