Home > Backend Development > PHP Tutorial > Example of finding the maximum value of consecutive elements in an array of positive and negative numbers in PHP_PHP Tutorial

Example of finding the maximum value of consecutive elements in an array of positive and negative numbers in PHP_PHP Tutorial

WBOY
Release: 2016-07-13 10:32:58
Original
731 people have browsed it

php implements the maximum subsequence of positive and negative arrays. It is required to give an array, which consists of positive and negative numbers, and find the maximum value of the subarray composed of consecutive elements in the array.
This is actually a backpack variant.

Copy code The code is as follows:

$list = array(1,-3,- 5,-7,8,9,-11,5);

$cur = 0;
$term = 0;
$res = 0;
$begin = 0;

foreach($list as $k => $v){
$cur += $v;
if($cur < 0){
$cur = 0;
$begin = $k + 1;
}
if($cur > $res){
$res = $cur;
$term = $k;
}
}
$max_seq = array_slice($list, $begin, ($term - $begin) + 1);

echo $res . ',';
print_r($max_seq);
//17,Array ( [0] => 8 [1] => 9 )

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752919.htmlTechArticlephp implements the maximum subsequence of positive and negative arrays. It is required to give an array. The array consists of positive and negative numbers. Find Find the maximum value of a subarray consisting of consecutive elements in the array. This actually has to be considered a back...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template