This commit is contained in:
2026-06-13 03:04:54 +10:00
parent 5022093fad
commit ec07a9322b
23 changed files with 208 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
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}))
}
+43
View File
@@ -0,0 +1,43 @@
package top100liked
import "testing"
// 爆内存
// func maxSubArray(nums []int) int {
// l := len(nums)
// msa := make([][]int, l)
// for i := range msa {
// msa[i] = make([]int, l)
// }
// res := nums[0]
// for i, v := range nums {
// msa[i][i] = v
// res = max(res, v)
// }
// for i := range l {
// for j := i + 1; j < l; j++ {
// msa[i][j] = msa[i][j-1] + nums[j]
// res = max(res, msa[i][j])
// }
// }
// return res
// }
func maxSubArray(nums []int) int {
dp := make([]int, len(nums))
dp[0] = nums[0]
maxSoFar := nums[0]
for i := 1; i < len(nums); i++ {
dp[i] = max(nums[i], dp[i-1]+nums[i])
maxSoFar = max(maxSoFar, dp[i])
}
return maxSoFar
}
func TestS13(t *testing.T) {
println(maxSubArray([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}))
println(maxSubArray([]int{1}))
println(maxSubArray([]int{5, 4, -1, 7, 8}))
println(maxSubArray([]int{-2, 1}))
}