Created
November 11, 2018 20:44
-
-
Save dkorpar/53f8c781a06b530bbab58fbe026ddc55 to your computer and use it in GitHub Desktop.
Subarray for the given sum
This file contains hidden or 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 | |
/* | |
* 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