c++ solution (greedy)


  • 0
    class Solution {
    public:
      int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n == 0) return 0;
        int profit = 0, buy = prices[0];
        for (int i = 1; i < n; ++i) {
          int tmp = prices[i] - buy;
          while (prices[i] - buy > tmp && i < n) {
            tmp = prices[i] - buy;
            i++;
          }
          if (tmp > 0) profit += tmp;
          buy = prices[i];
        }
        return profit;
      }
    };
    

Log in to reply
 

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