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.