Greedy using C++


  • 0
    F
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.size() == 0) return 0;
            int mv = 0, status = 0, len = prices.size(); 
            for (int i = 0; i < len; i++) {
                if (status == 1) {
                    status = 0;
                    mv += prices[i]; // sell
                }
                if (i < len -1 && prices[i] < prices[i + 1] && status == 0) { // buy
                    status = 1;
                    mv -= prices[i];
                }
            }
            return mv;
        }
    };
    
    

Log in to reply
 

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