FunctionRacerProblemsRace

Trim Both Ends to a Total

MediumTwo pointersPython, JavaScript, TypeScript, Java, C++

All items of nums are positive. You repeatedly remove either the first or the last remaining item, and you stop as soon as the removed items add up to exactly goal. Return the fewest removals that can reach goal, or -1 if no sequence of removals does.

The removed items always form a prefix plus a suffix of nums, so what remains is a contiguous middle stretch whose sum is the total of nums minus goal; the longest such stretch gives the fewest removals. Removing every item is allowed, and the middle stretch may then be empty.

Example 1

nums [1,1,4,2,3]
goal 5
returns 2

Remove the last item 3 and then the new last item 2: 3 + 2 = 5 in two removals.

Example 2

nums [5,6,7,8,9]
goal 4
returns -1

The smallest item is 5, so no removal can total exactly 4.

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