[勇者闯LeetCode] 53. Maximum Subarray
Description
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array[-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray[4,-1,2,1]
has the largest sum =6
.
Information
- Tags: Array | Dynamic Programming | Divide and Conquer
- Difficulty: Easy
Solution
扫描nums
,用两个变量分别保存当前subarray的和,与当前所有subarray的和的最大值。
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans, s = nums[0], nums[0]
for x in nums[1:]:
if (s < 0):
s = x
else:
s += x
ans = max(ans, s)
return ans