Skip to content

Instantly share code, notes, and snippets.

@jochemd
Created November 9, 2014 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jochemd/de9072a03793a997973a to your computer and use it in GitHub Desktop.
Save jochemd/de9072a03793a997973a to your computer and use it in GitHub Desktop.
For a given array and a given threshold, return the subarray which contains the longest run of consecutive numbers which - in total - are equal-to or less than the threshold. (see http://blog.adamcameron.me/2014/11/something-for-weekend-wee-code-quiz-in.html)
<?php
$threshold = 500;
// Test cases
$tests = [
// empty array
[[], []]
// one element array
, [[1], [1]]
// more element array
, [[1,2,3], [1,2,3]]
// no result array
, [[501, 502, 503], []]
// one result array
, [[501, 1, 502, 503], [1]]
// more result array
, [[501, 1, 2, 502, 503], [1,2]]
// first result array
, [[1, 2, 501, 502, 503], [1,2]]
// last result array
, [[501, 502, 503, 1, 2], [1,2]]
// exactly threshold
, [[501, 499, 502, 499, 1, 502, 503], [499,1]]
// Adams array
, [[100, 300, 100, 50, 50, 50, 50, 50, 500, 200, 100], [100, 50, 50, 50, 50, 50]]
];
// run tests
foreach ($tests as $value) {
if (getSubSeries($value[0], $threshold) !== $value[1]) {
echo "\n\nError for input\n";
var_dump($value[0]);
echo "\n expected\n";
var_dump($value[1]);
echo "\n got\n";
var_dump(getSubSeries($value[0], $threshold));
}
}
function getSubSeries($inputArray, $threshold) {
$window = [];
$bestSoFar = [];
while (sizeof($inputArray) > 0) {
// add to the window until it breaks
while(array_sum($window) <= $threshold && sizeof($inputArray) > 0) {
array_push($window, array_shift($inputArray));
}
// if window is longer than bestSoFar, add it
if(sizeof($window) > sizeof($bestSoFar)) {
$bestSoFar = $window;
// fix breakage
if(array_sum($bestSoFar) > $threshold) {
array_pop($bestSoFar);
}
}
// drop elements from window till it is unbroken
while(array_sum($window) > $threshold) {
array_shift($window);
}
}
return($bestSoFar);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment