mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
49 lines
696 B
Go
49 lines
696 B
Go
package leetcode
|
|
|
|
// 解法一 DP
|
|
func maxSubArray(nums []int) int {
|
|
if len(nums) == 0 {
|
|
return 0
|
|
}
|
|
if len(nums) == 1 {
|
|
return nums[0]
|
|
}
|
|
dp, res := make([]int, len(nums)), nums[0]
|
|
dp[0] = nums[0]
|
|
for i := 1; i < len(nums); i++ {
|
|
if dp[i-1] > 0 {
|
|
dp[i] = nums[i] + dp[i-1]
|
|
} else {
|
|
dp[i] = nums[i]
|
|
}
|
|
res = max(res, dp[i])
|
|
}
|
|
return res
|
|
}
|
|
|
|
// 解法二 模拟
|
|
func maxSubArray1(nums []int) int {
|
|
if len(nums) == 1 {
|
|
return nums[0]
|
|
}
|
|
maxSum, res, p := nums[0], 0, 0
|
|
for p < len(nums) {
|
|
res += nums[p]
|
|
if res > maxSum {
|
|
maxSum = res
|
|
}
|
|
if res < 0 {
|
|
res = 0
|
|
}
|
|
p++
|
|
}
|
|
return maxSum
|
|
}
|
|
|
|
func max(a int, b int) int {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|