Skip to content

Instantly share code, notes, and snippets.

@xorspark

xorspark/getSubseries.php Secret

Last active Aug 29, 2015
Embed
What would you like to do?
<?php
function getSubseries($series, $threshold) {
$subseries = [];
$tempSubseries = [];
$sum = 0;
$seriesLen = count($series);
for ($i = 0; $i < $seriesLen; ++$i) {
if ($sum + $series[$i] <= $threshold) {
$tempSubseries[] = $series[$i];
$sum += $series[$i];
}
else {
if (count($tempSubseries) > count($subseries)) {
$subseries = $tempSubseries;
}
if ($series[$i] > $threshold) {
$sum = 0;
$tempSubseries = [];
}
else {
$sum -= array_shift($tempSubseries);
if ($sum + $series[$i] > $threshold) {
$tempSubseries = [$series[$i]];
$sum = $series[$i];
}
else {
$sum += $series[$i];
$tempSubseries[] = $series[$i];
}
}
}
}
if (count($tempSubseries) > count($subseries)) {
return $tempSubseries;
}
else {
return $subseries;
}
}
$series = [100, 300, 100, 50, 50, 50, 50, 50, 500, 200, 100];
$threshold = 500;
var_export(getSubseries($series, $threshold));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.