[Introduction to Algorithms] Exercise 4.1-5 maximal continuous subarray problem

Source: Internet
Author: User

Title: The largest contiguous subarray of non-recursive arrays (contiguous and maximal subarray) in linear time.

Idea: Set the maximum subarray to Max, the start and end positions are S, E, the and of the sub-arrays being scanned are add, the start and end positions are I, J. The initial value of Max is-∞.

1. If the value of the array is all negative, the maximum value is returned.

2. Scan the array elements individually, updating the values of add, I, J.

A. If the value of add is positive, then the value for Max, S, and E is updated to add, I, J, if it is greater than Max's value.

B. If the value of add is negative, then the number of the paragraph from I to J can only reduce the and of the sub-array, to discard, add value clear 0 and the next element to start the calculation again, update the values of I, J.

#include <iostream>using namespacestd;inta[ -];intMain () {intsize; CIN>>size; BOOLneg_flag=true;//The maximum value is returned when all are negative.     intneg_max=-1e10;  for(intI=0; i<size;i++) {//enter and determine if all is negative. Cin>>A[i]; if(a[i]>=0) {Neg_flag=false; }        if(a[i]>Neg_max) {Neg_max=A[i]; }    }    if(neg_flag==true) {cout<<"Max is"<<neg_max<<"start from"<<neg_max<<" to"<<neg_max<<Endl; return 0; }    intMax=-1e10;//Max and.     ints=-1;//The maximum sub-array start point.     inte=-1;//The maximum sub-array end point.     intAdd=0;//scans sub-arrays and.     intI=0;//scans the start of a sub-array.     intj=0;//scans the end of the sub-array.      while(j<size) {Add+=A[j]; if(add>=0){            if(add>=max) {Max=add; S=i; E=J; }            ++J; }        Else{            ++J; I=J; if(j<size) {Add=0; } }} cout<<"Max is"<<max<<"start from"<<A[s]<<" to"<<A[e]<<Endl;} 

[Introduction to Algorithms] Exercise 4.1-5 maximal continuous subarray problem

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.