[Leetcode series] maximum continuous subcolumn recursive Solution Analysis

Source: Internet
Author: User

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 };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.