PHP implements two solutions to the maximum and problem of Continuous sub-arrays: array 2
The example in this article describes two solutions for PHP to find the largest continuous sub-array and the problem. We will share this with you for your reference. The details are as follows:
Problem description
Returns the largest sum of sub-arrays.
Description:
Enter an integer array, and the array contains positive and negative numbers.
One or more consecutive integers in the array form a sub-array. Each sub-array has a sum.
Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ).
There are two solutions to the maximum number of consecutive subarrays and this problem. One is dynamic planning.
The solution is as follows:
function getMaxSubSum($arr){ $curSum = $arr[0]; $maxSum = $arr[0]; for($i = 1; $i < count($arr); $i++){ if($curSum > 0) $curSum += $arr[$i]; else $curSum = $arr[$i]; if($curSum > $maxSum) $maxSum = $curSum; } return $maxSum;}
Scan Method
function getMaxSubSum($arr){ $curSum = 0; $maxSum = 0; for($i = 0; $i < count($arr); $i++ ){ $curSum += $arr[$i]; if($curSum <= 0) $curSum = 0; if($curSum > $maxSum) $maxSum = $curSum; } if($maxSum == 0){ $maxSum = $arr[0]; for($i = 1; $i < count($arr); $i++){ if($maxSum < $arr[$i] ) $maxSum = $arr[$i]; } } return $maxSum;}