[leetcode-in-go] 0053-Maximum Subarray

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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章