Skip to content

Instantly share code, notes, and snippets.

@bishwanathjha
Created October 23, 2016 15:28
Show Gist options
  • Save bishwanathjha/8b111c2ad75ca8142044b8ce9e73e0c1 to your computer and use it in GitHub Desktop.
Save bishwanathjha/8b111c2ad75ca8142044b8ce9e73e0c1 to your computer and use it in GitHub Desktop.
Largest Sum Contiguous Subarray in PHP
<?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