php實現正負數數組最大子序列,要求給出數組,該數組由正負數字組成,找出該數組中連續元素組成的子數組的最大值。
這其實得算是個背包變種吧。
復制代碼 代碼如下:
<?php
$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 )