C++ short code with comment lines - welcome questions


  • 0
    S
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int len = prices.size();
            if(len == 0)return 0;
            int result = 0;
            int min;//the minimum of "a day's price - if I buy a stone on this day the most I can get before this day"
            // so if here comes a new day i, and we 'd like to sell a stone on the new day, the most we can get is price[i]-min.
            int preget = 0;//the most we can get on the end of yesterday
            int prepre = 0;//the most we can get on the end of the day before yesterday, which means leave yesterday to cool down
            
            min = prices[0];
            for(int i=1;i<len;i++){
                if (prices[i] - min>result)result = prices[i] - min;// update the result first
                if((prices[i]-prepre)<min)min = prices[i]-prepre;//update min
                prepre = preget;
                preget = result;
                
            }
            return result;
            
        }
    };
    

Log in to reply
 

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