topic
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.
A thought:
Dynamic Programming. An array subscript to put the nums [i] array at the end of the maximum value of i is a lattice.
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)
Thinking two:
As long as the number in front of the plus and> 0, you can always add down. But <0 that this section would not take it.
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)
This approach is seen in the analysis in, really amazing