Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解题思路
- 负数和不可能是最大串的前缀
- 注意全部是负数的情况,因此 max 初值不是 0(这里按照 32 位整数最小值,能 PASS)
func maxSubArray(nums []int) int {
max, sum := -1<<31, 0
for _, v := range nums {
sum += v
if sum > max {
max = sum
}
if sum < 0 {
sum = 0
}
}
return max
}

本文探讨了如何寻找一个整数数组中具有最大和的连续子数组的问题,并给出了一种O(n)复杂度的解决方案。通过实例[-2,1,-3,4,-1,2,1,-5,4]展示了解法的有效性。
1561

被折叠的 条评论
为什么被折叠?



