Samples in the capsules
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- comparisons
- loops
- lists
Problem
Mariam Haddad, a mission engineer, is planning the return of the rocks from Mars. The rover stores them in capsules with the same weight limit and follows a fixed rule: each rock goes into the first open capsule where it still fits; if it fits in none, the rover opens a new one. Write a function that takes limit, the most a capsule can hold (a whole number greater than 0), and weights, the rock weights in the order they are picked up: whole numbers from 1 to limit; the list may be empty. Each rock goes into the first capsule, in opening order, where its load plus the rock doesn't go over limit (reaching it exactly is fine); if it fits in none, a new capsule is opened at the end. A stored rock never moves. Return how many capsules were opened.
With limit 10 and [6, 5, 4, 3, 7, 2]: 6 opens capsule 1, 5 opens 2, 4 fills 1, 3 goes into 2 (now 8), 7 opens 3 and 2 fits exactly in 2; it returns 3. With no rocks, it returns 0.
Examples
The example
10, [6, 5, 4, 3, 7, 2] → 3
No rocks
10, [] → 0
One rock that fills its capsule
5, [5] → 1
Reaching the limit exactly is fine
10, [5, 5, 5, 5] → 2
A rock goes back to the first capsule
10, [6, 6, 4, 4] → 2
Each rock fills a capsule
3, [3, 3, 3] → 3
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def capsules(limit, weights):
passJavaScript
function capsules(limit, weights) {
}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.