The maximal subarray of the algorithm

Source: Internet
Author: User

The maximum number of word groups is a classical problem in recursion and divide-and-conquer algorithms:

Problem: A sub-array in which the maximum value can be obtained by adding an array, which refers to any successive paragraph in the original array

Code:

#include  <iostream>using  namespace std;int max_mid (Int *a,int mid, Int low,int high) {    int ml = a[mid];    int  mr = 0;    int sum = ml;    for (int  i = mid-1; i>=low; i--)     {         sum = sum+a[i];        if (SUM&GT;ML)          {             ml = sum;        }    }     sum = 0;    for (int i = mid+1; i<=high;  i++)     {        sum = sum+a[i];     &nbSp;   if (SUM&GT;MR)         {             mr = sum;        &NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;ML+MR;} Int max (Int *a,int low,int high) {    if (Low == high)      {        return a[low];     }    else    {        int  mm;        int ml;         int mr;        int mid =  (Low+high)/2;         ml = max (A,low,mid);         mm = max_mid (A,mid,low,high);        mr = max (A,mid+1,high);         if (MM&GT;=ML&AMP;&AMP;MM&GT;=MR)         {             return mm;         }        if (ML&GT;=MM&AMP;&AMP;ML&GT;=MR)         {             return ml;        }         else        {             return mr;        }     }}int a[1000];int main () {    int n;     while (cin>>n) &NBSP;&NBSP;&NBSP;&NBSp {        for (int i = 0; i<n; i++)          {             cin>>a[i];        }         cout<<max (a,0,n-1) <<endl;    }    return  0;}







This article is from the "developer" blog, so be sure to keep this source http://tang1513.blog.51cto.com/7678175/1566341

The maximal subarray of the algorithm

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.