golang, with simple explanation.


  • 0

    In the traveral, we maintain the min_price and max_profit we can get.

    Consider at i-th day we sold out the stock. so in the i-th day, max_profit we can get
    is prices[i] - min_price. After we traversal every day. we can get the max_profit
    of the all.

    
    func maxProfit(prices []int) int {
    	if len(prices) == 0 {
    		return 0
    	}
    
    	min_price := math.MaxInt32
    	max_profit := 0
    
    	for i := 0; i < len(prices); i++ {
    		if prices[i] < min_price {
    			min_price = prices[i]
    		} else {
    			profix := prices[i] - min_price
    			if profix > max_profit {
    				max_profit = profix
    			}
    		}
    	}
    
    	return max_profit
    }
    
    

Log in to reply
 

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