Please improve my one-pass 7 line C++ code.


  • 4
    S

    The idea is to keep a running temporary variable to keep track of minimum and at each time try if there's a profit in selling at current time (and buying when it's minimum we kept track of). Could there be a more elegant solution?

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if (prices.size()<=1) return 0;
            
            int best_profit = 0;
            int prev_floor = prices[0];
            
            for (int i=1; i<prices.size(); i++){
                best_profit = max(best_profit, prices[i] - prev_floor);
                prev_floor  = min(prev_floor, prices[i]);
            }
            return best_profit;
        }
    };

  • 0
    B

    Same idea as yours but less codes.

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int res = 0, lp = INT_MAX;
            for (int i = 0; i < prices.size(); i++) {
                if (prices[i] < lp)         lp = prices[i];
                else if (prices[i] > lp)    res = max(prices[i] - lp, res);
            }
            return res;
        }
    };
    

  • 0
    S

    Hmm.. I doubt this code will be faster than mine because this code has branching inside the loop. Any C++ expert out there to shed light on this?


Log in to reply
 

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