Minimum Operations to Reduce X to Zero
Real-world version: Loading Crates From Both EndsThe statement here is our own: the same inputs, outputs and technique.
Crates stand in a single row on a loading dock. Crate i weighs weights[i] kilograms.
A picker can reach only the two ends of the row: one lift takes either the crate at the far left or the crate at the far right and puts it in the van. Once a crate is lifted the row closes up, so its neighbour becomes the new end of the row.
The van has to leave carrying exactly capacity kilograms. Return the smallest number of lifts that gets the loaded weight to exactly capacity, or -1 if no sequence of lifts reaches that weight. A lift count is never negative, so -1 can only mean the load is unreachable.
Examples
Example 1
- Input
- weights = [3, 2, 20, 1, 4], capacity = 7
- Output
- 2
Lift the 3 kg crate from the left end and the 4 kg crate from the right end. The van carries 3 + 4 = 7 kilograms after two lifts.
Example 2
- Input
- weights = [1, 1, 1, 9, 5], capacity = 12
- Output
- 4
Lift the three 1 kg crates off the left end, which brings the 9 kg crate to that end, then lift it as well. Four lifts carry 12 kilograms.
Example 3
- Input
- weights = [2, 4, 6], capacity = 5
- Output
- -1
No run of lifts off the two ends adds up to 5 kilograms, so the van cannot leave loaded as asked and the answer is -1.
Example 4
- Input
- weights = [4, 4, 4, 4], capacity = 16
- Output
- 4
Lifting all four crates loads 16 kilograms, which is the requested weight, so four lifts are used.
Constraints
- 1 <= weights.length <= 10^5
- 1 <= weights[i] <= 10^4
- 1 <= capacity <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def fewest_crates(weights: list[int], capacity: int) -> int:public int fewestCrates(int[] weights, int capacity)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 18 test cases: 18 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Max Consecutive Ones IIIReal-world version: Longest Verified Backup StreakMedium
- Subarray Product Less Than KReal-world version: Safe Stretches of the Filter CascadeMedium
- Minimum Size Subarray SumReal-world version: Fewest Shifts to Clear the QuotaMedium
- Count Number of Nice SubarraysReal-world version: Runs With K Odd ReadingsMedium