Splitting the honey
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- lists
- comparisons
Problem
The sisters Rosa and Lidia Paredes look after the beehives their grandfather left them. At the end of the harvest they split the combs, but a comb is never cut: each one goes whole to one sister or the other. They both want to take home weights as close as possible.
Write a function that takes combs, a list of positive whole numbers with the weight of each comb (it may be empty and weights may repeat), and returns a whole number: the smallest possible difference between the weight Rosa takes and the weight Lidia takes. Every comb gets handed out, and one sister may end up with none.
With [3, 3, 2, 2, 2], Rosa takes the two 3s and Lidia the three 2s:
6 against 6, so it returns 0. With [7, 3, 2] the most even split is 7 against 5, and it returns 2. With no combs, both take 0 and the difference is 0.
Examples
The example
[3, 3, 2, 2, 2] → 0
It never comes out even
[7, 3, 2] → 2
One comb outweighs all the others together
[20, 3, 4, 5] → 8
The combs that go together are not next to each other
[2, 5, 1, 4] → 0
No combs
[] → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def smallest_gap(combs):
passJavaScript
function smallestGap(combs) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.