PHP calculates the maximum subsequence and algorithm implementation. Copy the code as follows :? Php author: distant expectation QQ: 15624575 algorithm analysis: 1. it must be an integer sequence; 2. if the whole sequence is not all negative, the largest subsequence is the first
The code is as follows:
// Author: distant expectations
// QQ: 15624575
// Algorithm analysis: 1. it must be an integer sequence. 2. if the whole sequence is not all negative, the first item of the maximum subsequence must be a positive number, otherwise, the sum of the numbers after the largest subsequence plus the negative number of the first item is certainly not the largest; 3. if the whole sequence is negative, the sum of the largest subsequence is 0;
// The sequence of all negative numbers is very simple, not an example
$ Arr = array (4,-3, 5,-2,-1, 2, 6,-2 );
Function getmaxsum ($ arr ){
$ Thissum = 0;
$ Maxsum = 0;
$ Start = 0; // start subscript of the record subsequence
$ End = 0; // end subscript of the record subsequence
For ($ I = 0; $ I $ Thissum + = $ arr [$ I]; // Obtain the sum of the current subsequence
If ($ thissum> $ maxsum) {// if the sum of the current subsequence is greater than the sum of the current largest subsequence
$ Maxsum = $ thissum; // change the sum of the largest subsequences currently.
$ End = $ I;
} Else if ($ thissum <0) {// if the sum of the current subsequence is smaller than 0, the next element value is assumed as the first item of the largest subsequence, here, we can ensure that the first item of the largest auto-sequence must be a positive number.
$ Thissum = 0; // The prerequisite is that the sequence is not all negative.
$ Start = $ I + 1;
}
}
$ Parr = array ($ start, $ end, $ maxsum );
Return $ parr;
}
List ($ start, $ end, $ maxsum) = getmaxsum ($ arr );
Echo 'the maximum subsequence is :';
For ($ I = $ start; $ I <= $ end; $ I ++ ){
Echo $ arr [$ I]. '';
}
Echo'
';
Echo 'the sum of the largest subsequences is '. $ maxsum;
?>
The http://www.bkjia.com/PHPjc/323639.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/323639.htmlTechArticle code is as follows :? Php // Author: distant expectation // QQ: 15624575 // algorithm analysis: 1. it must be an integer sequence. 2. if the whole sequence is not all negative, the first of the largest subsequence...