Last active
August 29, 2015 14:24
-
-
Save thachp/3395c9de03c22b1f2e12 to your computer and use it in GitHub Desktop.
Kadane's algorithm 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 | |
/** | |
* Kadane's algorithm for finding the MAXIMUM contiguous subsequence in a one-dimensional sequence. | |
* @author thachp | |
* Attributions: | |
* http://www.algorithmist.com/index.php/Kadane's_Algorithm | |
* http://www.turb0js.com/a/Kadane's_algorithm# | |
*/ | |
$array = array(-6, 1, -3, 4); | |
function max_subarray($array) | |
{ | |
$max_ending_here = 0; | |
$max_so_far = 0; | |
for($i=0; $i < count($array); $i++) | |
{ | |
$x = $array[$i]; | |
$max_ending_here = max(0, $max_ending_here + $x); | |
$max_so_far = max($max_so_far, $max_ending_here); | |
} | |
return $max_so_far; | |
} | |
// expect 4 | |
echo (max_subarray($array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment