golang solution


  • 0
    func maxProfit(prices []int) int {
    	profit := 0
    	n := len(prices)
    	k := 0
    
    	// k is buy day
    	// l is sell day
    
    	for {
    		// find k, such that prices[k] < prices[k+1]
    		for k < n-1 {
    			if prices[k] < prices[k+1] {
    				break
    			}
    			k++
    		}
    
    		// find l, such that l > k and prices[l] > prices[l+1]
    		l := k + 1
    		for l < n {
    			if l == n-1 || (prices[l] > prices[l+1]) {
    				break
    			}
    			l++
    		}
    
    		if l < n {
    			profit += (prices[l] - prices[k])
    			// next k
    			k = l + 1
    		} else {
    			break
    		}
    	}
    
    	return profit
    }
    
    
    

Log in to reply
 

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