What if I can always forsee the next second of stock...


  • 0
    T

    The key to solve it is always sell when you know the price of the stock will fall in the next step.

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

Log in to reply
 

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