53_Maximum Subarray
[Easy][Array, Dynamic Programming]
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
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 1: dynamic programing, bottom-up
Idea:
If we have the solution for nums[0, n-1], what's the solution when we add one extra integer nums[n-1]? There are two possibilities for the max in nums[0, n]:
nums[n-1] is not included: in this case the max in nums[0, n] equals to the max in nums[0, n-1].
nums[n-1] is included: in this case we need to know the max in nums[0, n-1] that includes nums[n-2], which we call curMaxSum. Then update curMaxSum with the max of two cases: 1) just have nums[n-1] itself; 2) add nums[n-1] to curMaxSum.
Need to store two values when we iterate over the nums: 1) the max of sum for any subarray; 2) the max of sum for subarray includes the last element.
Time Complexity:
Space Complexity:
Solution 2: Divide and Conquer, Recursive
Idea:
divides the array into left and right halves and recursively solves for both of them to get the max sum for each half.
For the right half, compute the max sum if the first element is included.
For the left half, compute the max sum if the last element is included.
Merge: the result for the combination of the 2 sub arrays is the maximum of the following : 1. solution for left sub array, 2. solution for right sub array, 3. max sum in the left subarray with the last element + max sum in the right array with the first element
Time Complexity:
Space Complexity:
Last updated