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.
Solution
Approach 1: o(n)
currSum = max(nums[i], currSum+nums[i]) # The maximum value before the nums[i]
maxSum = max(currSum, maxSum) #previous maximum
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
currSum = nums[0]
maxSum = nums[0];
i = 1
while(i < len(nums)):
currSum = max(nums[i], currSum+nums[i])
maxSum = max(currSum, maxSum)
print(currSum, maxSum)
i += 1
return maxSum
Approach 2: the divide and conquer approach
...
来源:oschina
链接:https://my.oschina.net/u/4228078/blog/4311443