给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
解答
动态规划
func maxProfit(prices []int) int {
if len(prices) == 0 {
return 0
}
n := len(prices)
dp := make([][2]int, n)
for i := 0; i < n; i++ {
// 这里为了避免dp数组出现dp[-1]的状态
if i == 0 {
dp[i][0] = 0
dp[i][1] = -prices[i]
continue
}
// 今天没有股票,有两种情况。1、今天没有操作,也就是我昨天就没有股票;2、今天我把股票卖了,也就是我昨天手里是有股票的,再加上股票今天的价格
dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
// 今天手里有股票,有两种情况。1、今天没有操作,股票是昨天买的;2、今天刚买的股票,因为题意是只能买一次,那就是当天股票价格的负数
dp[i][1] = max(dp[i-1][1], -prices[i])
}
return dp[n-1][0]
}
func max(x, y int) int {
if x >= y {
return x
}
return y
}
求最大值
价格趋势图,如下:

根据趋势图,我们只要找到最低点和最大利润就可以了
func maxProfit(prices []int) int {
minProfit := math.MaxInt64
maxProfit := 0
for i := 0; i < len(prices); i++ {
if prices[i] < minProfit {
minProfit = prices[i]
} else if (prices[i] - minProfit) > maxProfit {
maxProfit = prices[i] - minProfit
}
}
return maxProfit
}
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
示例 2:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
解答
动态规划
求最大值
价格趋势图,如下:

根据趋势图,我们只要找到最低点和最大利润就可以了