Question
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
Explanation
Assume the local maximum is the maximum value of the continuous subarray which must contain the current value pointed by the index i. The function of local maximum can be expressed as localMax[i] = max(nums[i], localMax[i-1]+nums[i])
. This can be explained by the examples below:
- if localMax[i-1]>0, nums[i]>0 then localMax[i] = localMax[i-1]+nums[i]
- if localMax[i-1]>0, nums[i]<0 then localMax[i] = localMax[i-1]+nums[i]
- if localMax[i-1]<0, nums[i]>0 then localMax[i] = nums[i]
- if localMax[i-1]<0, nums[i]<0 then localMax[i] = nums[i]
We also need a globalMax
to store the global maximum value. In this case, although we take localMax[i-1]+nums[i]
as local maximum which is smaller than localMax[i-1]
when localMax[i-1]>0, nums[i]<0
, we are still able to keep the localMax[i-1] with the existence of globalMax
. With these two variables, we can get maximum of subarray with O(n) time complexity and O(1) space complexity.
Code
1 | class Solution: |