Maximum sub-array 2

Source: Internet
Author: User

I wrote an introduction to Algorithm Implementation Method last time. Then I continued to read the exercise questions and found that I could implement the O (n) Complexity Algorithm in a simpler way. The idea is to record the largest subarray currently processed by the record from the left, and then perform continuous record. If the addition is less than 0, set it to 0 and continue the addition and solution!

The Code is as follows:


[Cpp]
Int Find_MaxiMum_SubArray2 (int * A, int low, int high, int & max_left, int & max_right, int & max_value)
{
Max_left = low;
Max_right = low;
 
Max_value = 0;
 
Int ThisSum = 0;
Int tmp_left = low;
For (int I = low; I {
ThisSum + = A [I];
If (ThisSum> max_value)
{
Max_value = ThisSum;
Max_right = I;
Max_left = tmp_left;
}
Else if (ThisSum <0)
{
ThisSum = 0;
Tmp_left = I + 1;
}
 
}
 
Return 0;
}

Int Find_MaxiMum_SubArray2 (int * A, int low, int high, int & max_left, int & max_right, int & max_value)
{
Max_left = low;
Max_right = low;

Max_value = 0;

Int ThisSum = 0;
Int tmp_left = low;
For (int I = low; I {
ThisSum + = A [I];
If (ThisSum> max_value)
{
Max_value = ThisSum;
Max_right = I;
Max_left = tmp_left;
}
Else if (ThisSum <0)
{
ThisSum = 0;
Tmp_left = I + 1;
}

}

Return 0;
}
It is found that the code is shorter and the time complexity is better.

 


 

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.