All problems
0499MediumArrayHash TableBinary SearchSliding WindowPrefix Sum

Loading Crates From Both Ends

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1658Minimum Operations to Reduce X to Zero

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_crates(weights: list[int], capacity: int) -> int:
Java
public int fewestCrates(int[] weights, int capacity)
September 7
Apply