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
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.
$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 )