FunctionRacerProblemsRace

Best Pick With Small Gaps

HardStacks and queuesPython, JavaScript, TypeScript, Java, C++

Pick one or more items of nums and keep them in their order. Two items that follow each other in the pick must be at most k positions apart in nums.

Return the largest sum a pick can have.

Example 1

nums [4,-6,-7,5]
k 3
returns 9

The 4 and the 5 are three positions apart, so they can be picked together.

Example 2

nums [4,-6,-7,5]
k 2
returns 5

Now the 4 and the 5 are too far apart, and bridging the gap would cost at least 6. The 5 alone is best.

Example 3

nums [-3,-8]
k 1
returns -3

At least one item must be picked, and -3 is the smaller loss.

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 Stacks and queues problems