FunctionRacerProblemsRace

Lighten the Shelf

BeginnerTwo pointersPython, JavaScript, TypeScript, Java, C++

A shelf holds a row of boxes, and weights lists their weights from left to right. The shelf can carry limit kilograms. While the boxes on it weigh more than limit in total, one box is taken away from an end of the row: the heavier of the two end boxes, or the right one if both weigh the same.

Return how many boxes are taken away.

Example 1

weights [4,2,7,3]
limit 9
returns 2

The boxes weigh 16. The left end (4) is heavier than the right end (3), so 4 goes. Then 3 beats 2 and goes. The rest weighs 9.

Example 2

weights [5,5]
limit 20
returns 0

The boxes weigh 10, which the shelf can carry.

Example 3

weights [6,1,6]
limit 0
returns 3

Nothing may stay. The ends tie, so the right 6 goes, then the left 6, then the 1.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Two pointers problems