mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 16:36:41 +08:00
规范格式
This commit is contained in:
48
leetcode/0053.Maximum-Subarray/53. Maximum Subarray.go
Normal file
48
leetcode/0053.Maximum-Subarray/53. Maximum Subarray.go
Normal file
@ -0,0 +1,48 @@
|
||||
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
|
||||
}
|
Reference in New Issue
Block a user