Created
October 23, 2016 15:28
-
-
Save bishwanathjha/8b111c2ad75ca8142044b8ce9e73e0c1 to your computer and use it in GitHub Desktop.
Largest Sum Contiguous Subarray in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Bishwanath Jha <bishwanathkj@gmail.com> | |
* Largest Sum Contiguous Subarray | |
*/ | |
function GetMaxSum($array) { | |
$total = $max_total = 0; | |
$count = count($array); | |
for($i = 0; $i < $count; $i++) { | |
$total += $array[$i]; | |
// Reset the total to 0 | |
if($total < 0) $total = 0; | |
// Update the max total if we have total more than max total | |
if($max_total < $total) $max_total = $total; | |
} | |
return $max_total; | |
} | |
$array = [1,-2,-3,-4,-5, 8, -7, 11]; | |
echo GetMaxSum($array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment