Skip to content

Instantly share code, notes, and snippets.

@dkorpar
Created November 11, 2018 20:44
Show Gist options
  • Save dkorpar/53f8c781a06b530bbab58fbe026ddc55 to your computer and use it in GitHub Desktop.
Save dkorpar/53f8c781a06b530bbab58fbe026ddc55 to your computer and use it in GitHub Desktop.
Subarray for the given sum
<?php
/*
* Find a subarray with the minimum number of items
* which sum is equal to the requested sum.
*
* Items [1, 2, 3, 5] and sum of 5 will return [5]
* Items [1, 2, 3, 5] and sum of 4 will return [1, 3]
* Items [1, 2, 3, 5] and sum of 8 will return [3, 5]
* Items [1, 2, 3, 5] and sum of 9 will return [1, 3, 5]
* Items [1, 2, 3, 5] and sum of 12 will return []
*/
function getSubCountItems($candidates, $sum, $items=[[]])
{
$newItems = [];
$count = count($candidates);
foreach ($items as $item) {
end($item);
$start = key($item) !== null ? key($item) + 1: 0;
for ($i = $start; $i < $count; $i++) {
$add = $item + [$i => $candidates[$i]];
$checkSum = array_sum($add);
if ($checkSum == $sum) {
return $add;
}
$newItems[] = $add;
}
}
if (!empty($newItems)) {
return getSubCountItems($candidates, $sum, $newItems);
}
return $newItems;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment