Problem
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
1 |
|
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
-
We are finding the maximum of a subarray, which means we need to continuosily adding numbers, also we need to return one maximum number, which means we need to have a variable to keep track of the maximum.
-
While iterating, the sum is keep adding current number. If the sum is less than the current number, we can just drop the sum, and reset the sum to the current number. And we compare the sum with the maximum result.
-
Finally, return the maximum result.
Solution 1
1 |
|
Explanation 2
- We can also use divide and conquer method to solve this problem. First, we divide the array into left half and right half, and find their max sum. We also need to find the max sum for the middle part which is crossing the left half and right half, and we can find it by starting from the middle number and scan left side and scan the right side. Finally, compare these three sums.
Solution 2
1 |
|