For more information, see discuss: leetcode.
Step 1. Select the intermediate element of the array. The maximum sub-sequence has two possibilities: including this element/Not including.
Step 2.
Step 2.1 If the largest sub-sequence does not contain intermediate elements, perform Step 1 on the left and right sub-sequences.
Step 2.2 If the maximum sub-sequence contains, the result is very simple, that is, the maximum suffix sub-column of the left sub-column (that is, containing the last element of the left sub-column-intermediate element) add the largest prefix of the right child column to the Child column (that is, it contains the first element of the Right child column-intermediate element)
Step 3. Return the maximum value of the three columns (the maximum value of the Left subcolumn and the maximum value of the right subcolumn ).
1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 if(n==0) return 0; 7 return maxSubArrayHelperFunction(A,0,n-1); 8 } 9 10 int maxSubArrayHelperFunction(int A[], int left, int right) {11 if(right == left) return A[left];12 int middle = (left+right)/2;13 int leftans = maxSubArrayHelperFunction(A, left, middle);14 int rightans = maxSubArrayHelperFunction(A, middle+1, right);15 int leftmax = A[middle];16 int rightmax = A[middle+1];17 int temp = 0;18 for(int i=middle;i>=left;i--) {19 temp += A[i];20 if(temp > leftmax) leftmax = temp;21 }22 temp = 0;23 for(int i=middle+1;i<=right;i++) {24 temp += A[i];25 if(temp > rightmax) rightmax = temp;26 }27 return max(max(leftans, rightans),leftmax+rightmax);28 }29 };