Golang concise solution


  • 0

    If the next day's share is greater than today, you can just buy today and sell it tomorrow.
    This is the way to maximize your profit.

    Let's say an array is as below:

    5, 7, 11
    

    If you buy 5 and wait 11, or you buy 5 and sell it at 7 and then buy 7 again and sell at 11, the profit is the same, 6. It's important to notice that waiting produces no greater profit to solve this problem.

    func maxProfit(prices []int) int {
    	profit, sell := 0, false
    
    	for i := 0; i < len(prices); i++ {
    		if sell {
    			profit, sell = profit+prices[i]-prices[i-1], false
    		}
    		sell = i < len(prices)-1 && prices[i] < prices[i+1]
    	}
    	return profit
    }
    

Log in to reply
 

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