/** * Created by PhpStorm. * User: lunweiwei * Date: 16/8/30 * Time: 上午11:15 */ $source = [-1, 1, 2, -5, 7]; function maxSub($source = []) { $max_item = max($source); if ($max_item <= 0) { return $max_item; } $max_sub_sum = 0; $sum = 0; $count = count($source); for ($i = 0; $i < $count; $i++) { if ($sum <= 0) { $sum = $source[$i]; } else { $sum += $source[$i]; } if ($max_sub_sum < $sum) { $max_sub_sum = $sum; } } return $max_sub_sum; } $max_sub_sum = maxSub($source); var_dump($max_sub_sum);
// 太复杂,看不懂 // 规则: // (1)任何可能产生最大和的子序列,首尾元素只能是正值。 // (2)如果某个序列和为负值,那么以这个序列开始的所有序列都不可能出现最大和,故忽略掉。 function maxSub2($arr) { $n = count($arr); $thisSum = $maxSum = 0; $s = $e = 0; for ($j = 0; $j < $n; $j++) { $thisSum += $arr[$j]; #echo 'j: ', $j, "\n"; #echo 'thisSum: ', $thisSum, "\n"; #echo 'maxSum: ', $maxSum, "\n"; #echo '---------------------', "\n"; if ($thisSum > $maxSum) { $maxSum = $thisSum; $e = $j; } elseif ($thisSum < 0) { $thisSum = 0; $e = $s = $j + 1; } } echo __FUNCTION__, "({$s}~{$e}): ", $maxSum, "\n"; } $arr = [4, -3, 5, -2, -1, 2, 6, -2]; $arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; #$arr = [ 4, 3, 5 ]; echo json_encode($arr), "\n"; maxSub($arr); maxSub2($arr);