Data structure and algorithm surface test questions 80 (3)

Source: Internet
Author: User

3. find the maximum and the sub-array

Title :

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 of the and of all sub-arrays. Requires a time complexity of O (n).

For example, the input array is 1,-2, 3, ten, -4, 7, 2,-5, and the largest subarray is 3, ten, -4, 7, 2,

So the output is the and of the subarray.

//starting with the first number plus, and credited as Sum, with a variable max record Max and, if and less than 0,sum=0, scan the entire array. #include <iostream>#include<cstdio>#include<limits>#include<vector>using namespacestd;#defineInt_min (numeric_limits<int>::min) ()intMain () {int_max=int_min,sum=0, Temp,i; Vector<int>_array; _array.reserve ( +);//set the container size to increase efficiency     while(~SCANF ("%d",&temp)) {        if(Temp>_max) _max=temp;//Record Maximum value_array.push_back (temp); }    if(_max<=0) {printf ("the array's sub-array is the largest and is:%d\n", _max); return 0; }     for(i=0; I<_array.size (); i++){        if(sum<0) sum=0; Sum+=_array[i]; if(Sum>_max) _max=sum; } printf ("the array's sub-array is the largest and is:%d\n", _max); return 0;}

Data structure and algorithm surface test questions 80 (3)

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.