48 lines
1.0 KiB
Go
48 lines
1.0 KiB
Go
package top100liked
|
|
|
|
import "testing"
|
|
|
|
// https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
|
|
|
|
// 贪心
|
|
func maxProfit(prices []int) int {
|
|
minPrice := prices[0] // 历史最低买入价
|
|
maxProfit := 0
|
|
|
|
for i := 1; i < len(prices); i++ {
|
|
// 如果今天卖,能赚多少?
|
|
profit := prices[i] - minPrice
|
|
maxProfit = max(maxProfit, profit)
|
|
|
|
// 更新历史最低价
|
|
minPrice = min(minPrice, prices[i])
|
|
}
|
|
return maxProfit
|
|
}
|
|
|
|
// 动态规划
|
|
// dp[n][0] 第 n 天手中不持有股票时的最大利润
|
|
// dp[n][1] 第 n 天手中持有股票时的最大利润
|
|
// func maxProfit(prices []int) int {
|
|
// n := len(prices)
|
|
// if n == 0 {
|
|
// return 0
|
|
// }
|
|
|
|
// dp := make([][2]int, n)
|
|
// dp[0][0] = 0
|
|
// dp[0][1] = -prices[0]
|
|
|
|
// for i := 1; i < n; i++ {
|
|
// dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
|
|
// dp[i][1] = max(dp[i-1][1], -prices[i])
|
|
// }
|
|
|
|
// return dp[n-1][0]
|
|
// }
|
|
|
|
func TestS13_1(t *testing.T) {
|
|
println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
|
|
println(maxProfit([]int{7, 6, 4, 3, 1}))
|
|
}
|