You need to check this answer out, in JAVA, with explaination.


  • 0
    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices == null || prices.length < 2)
                return 0;
            int maxProfit = 0;
            int bought = prices[0];
            for(int p: prices)
            {
                if(p > bought) 
                    maxProfit += p - bought;
                bought = p;
            }
            return maxProfit;
        }
    }
    

    Super concise. As long as the next day's price is higher than today's price, you buy it and sell it the next day. For sequence like 1 , 5, 9, we buy one day one, sell on day two, then buy on day 2 and then buy on day3. It is true that we cannot buy and sell on the same day. However the result is the same to buy on day one and sell on day three.
    So, to sum up, you buy it as long as the price today is lower than yesterday's price, and sell it as long as the next day's price is higher than today's price.


  • 0
    R

    How would this work in the case when your prices array is [3,1,9]. Since you are automatically buying on the first day, this will return maxProfit as 6 whereas it can actually be 8 if you bought at 1 and sold at 9.


  • 0

    @rajveer_90hotmail.com Oh, you are right. If I buy on the first day, I will get a wrong answer.
    However, here is the case. Suppose today is day i ( price is P1) and the second day is day i+1(Price is P2) , we want to update the status no matter P2 is greater or less than P1.
    1 If P2 > P1, we sell it, we got profit P2 - P1
    2 If P2 < P1, we rebuy it, which means we discard the stocks we bought and rebuy it on day i +1
    3 P2 =P1 does not matter

                if(p > bought) 
                    maxProfit += p - bought;
                bought = p;
    

    The above code lines does the job I described. This method is actually not conceptually right, but it works logically. Sorry for the misleading.


  • 0
    This post is deleted!

Log in to reply
 

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