leetcode 买卖股票 golang

372 阅读1分钟

1、只能有一次买入卖出的机会 LeetCode121
第几次卖出能得到的最大值是 前一次卖出得到的最大值和这次卖出得到的减去这次之前的最小值两者之间的大值。
max[i] = max(max[i-1], price[i]-minPrice)

func maxProfit1_1(prices []int) int {
	minPrice := prices[0]
	dp := make([]int, len(prices))
	dp[0] = 0
	for i := 1; i < len(prices); i++ {
		dp[i] = myMax(dp[i-1], prices[i]-minPrice)
		minPrice = myMin(minPrice, prices[i])
	}
	return dp[len(prices)-1]
}

也可以不使用数组,直接变量保存当前最大值即可。

func maxProfit(prices []int) int {
	maxProfit := 0
	minPrice := prices[0]
	for i := 1; i < len(prices); i++ {
		maxProfit = myMax(maxProfit, prices[i]-minPrice)
		minPrice = myMin(minPrice, prices[i])
	}
	return maxProfit
}

![](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/9/6/16d05ed51ed836f7~tplv-t2oaga2asx-image.image)

func myMax(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func myMin(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

2、可以多次买入卖出 LeetCode122

贪心,每次只要比上次有增长,就可以卖出。

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