英文原題
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.
中文原題
給定一個數組,找這個數組里具有最大和的連續子數組,并且返回對應的最大值
如果你找到了使用O(n)時間復雜度的解法,不妨也嘗試以下使用分治法解題。
最優題解
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(1, len(nums)):
nums[i] = nums[i] + max(nums[i-1], 0)
return max(nums)
這是一種動態規劃思維,代碼相當簡潔,只有三行。解題思路大概是:
- 遍歷列表
- nums[i] = nums[i] + max(nums[i-1]),這段代碼需要注意的是, nums[i-1]并不是與數組前一項相加,而是到前一項為止的最大子序和,和0比較是因為只要大于0,就可以相加構造最大子序和,如果小于零則相加為0,nums[i] = nums[i],相當于最大子序和歸零,重新計算。
暴力題解
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
tmp = nums[0]
max_ = tmp
n = len(nums)
for i in range(1, n):
if tmp + nums[i] > nums[i]:
max_ = max(max_, tmp+nums[i])
tmp = tmp + nums[i]
else:
max_ = max(max_, tmp, tmp+nums[i], nums[i])
tmp = nums[i]
return max_