leecode 122 买卖股票的最佳时机 II

func maxProfit(prices []int) int {
    var  result int
    for i:= 1; i < len(prices); i++{
        if prices[i] - prices[i-1] > 0 {
            result += prices[i] - prices[i-1]
        }
    }
    return result
}

方案二:

func maxProfit(prices []int) int {
    if len(prices) < 2 {
         return 0
    }
    buy, sell, result := -prices[0], 0, 0 
    for i:= 1; i < len(prices); i++{
        buy = max(buy, sell - prices[i])
        sell = max(sell, buy + prices[i])
        result = max(result, sell)
    }
    return result
}

func max(a, b int) int {
	fmt.Println(a,b)
	if a > b {
		return a
	}
	return b
}

你可能感兴趣的:(leetcode)