题目
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.
思路一:
用动态规划。一个数组,下标为i的格子放以 nums[i]结尾的最大array的值。
def maxSubArray(self, nums: List[int]) -> int:
dp = [0]*len(nums)
# 以nums[i]结尾的最大子序列的值
dp[0] = nums[0]
for i in range(1,len(nums)):
if dp[i-1] < 0:
dp[i] = nums[i]
else:
dp[i] = dp[i-1] + nums[i]
return max(dp)
思路二:
只要前面的数加和 > 0,就可以一直往下加。但是 < 0那这一部分就不用要了。
def maxSubArray(self, nums: List[int]) -> int:
for i in range(1,len(nums)):
if nums[i-1]>0:
nums[i] += nums[i-1]
return max(nums)
这个方法是在解析里看到的,真的很神奇