Returns the sum of the largest sub-arrays in an integer array

Source: Internet
Author: User

Title: Returns the and of the largest sub-array in an integer array.

Requirements:

Requires that the procedure be capable of handling 1000 elements;

Each element is of the int32 type;

Enter an array of shapes with positive and negative numbers in the array.

One or more consecutive integers in an array make up a sub-array, each of which has a and.

The maximum value for the and of all sub-arrays. Requires a time complexity of O (n).

Ideas:

Considering the manual input of 1000 elements, the system randomly 1000 elements are tested in the program. The code differs little from the previous code.

Program code:

1#include <iostream.h>2#include <stdlib.h>3 4 intMaxsum (intBintN)5 {  6      7     intsum=a[0];8     intb=0; 9     Ten      for(intI=0; i<n; i++)   One     {   A         if(b<0)//...   -b=A[i];  -         Else   theb+=A[i];  -         if(sum<b) -sum=b; -     }   +      returnsum; - }   +    A intMain () at {    -     intN; -cout<<"Please enter the number of elements in the array:"<<Endl; -Cin>>N; -cout<<"Please enter the elements of the array:"<<Endl; -     int*a=New int[n]; in     intx; -      for(intI=0; i<n;i++) to     { +X=rand ()-rand (); -a[i]=x; thecout<<a[i]<<" "; *     } $     Panax Notoginsengcout<<Endl; -Cout<<maxsum (a,n) <<Endl; the      +     return 0;  A}

Program:

Test for code overflow:

Will

    int x;      for (int i=0; i<n;i++)    {        x=rand ()-rand ();        A[i]=x;        cout<<a[i]<<"";    }

Revision changed to

    for (int i=0; i<n;i++)    {        cin>>a[i];    }

Program:

Feelings:

2^31-1=2147483647, the code overflows in the range of -2^31~2^31, beyond which is overflow. In the process of implementation of the program, mastered the use of random rand, using the call function, so that the program becomes "tall." But we still have room for improvement, so that we know more about it.

Returns the sum of the largest sub-arrays in an integer array

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.