Simple O(n) constant space solution


  • 0
    M
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int maxprof=0, res=0,  tempprof;
    
            for(int i=0; i<prices.size()-1; i++)
            {
                tempprof=prices[i+1]-prices[i];
                if(tempprof>=0)
                {
                    maxprof+= tempprof;
                    res=(maxprof>res)?maxprof:res;   //check current max prof with res and update
                }
                else // if(tempprof<0)
                {
                    if(maxprof+tempprof >=0)
                    {
                        maxprof+=tempprof;
                        res= (maxprof>res)?maxprof:res;   //check current max prof with res and update
                    }
                    
                    else   //scrap all previous prof calculation coz its negative. NO USE.
                    maxprof=0;
                }
            }
            return res;
        }
    };

Log in to reply
 

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