Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
====================================================================================
Consider an array A[i,....,j,j+1]. If we know its lagest subarrya is A[i,...,j].
Then the new array's lagest sum subarray may same as the array A[i,...j], or is A[i,...j,j+1].
That's only depends on if A[j+1] is larger than sum(A[i,...j]).
1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 int max_sum = INT_MIN; 6 int sum = 0; 7 for(int i = 0; i < n; i++) { 8 sum = max(sum + A[i], A[i]); 9 max_sum = max(max_sum, sum); 10 } 11 return max_sum; 12 13 } 14 };