欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[leetcode-in-go] 0053-Maximum Subarray

最编程 2024-06-07 20:05:08
...

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
}