Shortest Steep Climb

Mediumsliding windowAlso known as Minimum Size Subarray Sum

A cycling coach plans hill training on a mountain road split into equal segments. The map lists how many metres each segment climbs, in order. The road only goes up, so every number is positive.

Today's drill is to climb at least target metres without stopping, over as few segments as possible. The coach wants the shortest unbroken stretch that climbs that much.

Your task

Write shortestClimb(gains, target). Return the smallest number of consecutive segments whose gains add up to at least target.

If no stretch climbs enough, not even the whole road, return 0.

shortestClimb(gains: int[], target: int) → int

Examples

Example 1
Input
gains = [30, 10, 60, 20, 40, 50]
target = 100
Output
3
Why

Segments 4 and 5 climb 40 + 50 = 90, which is just short. Segments 3 to 5 climb 20 + 40 + 50 = 110, and segments 0 to 2 climb exactly 100, which counts. No pair of neighbouring segments reaches 100, since the largest pair climbs 90, so the answer is 3.

Example 2
Input
gains = [5, 5, 5]
target = 20
Output
0
Why

The whole road climbs only 15 metres, so no stretch reaches 20 and the answer is 0.

Constraints

  • 0 ≤ gains.length ≤ 10,000
  • 1 ≤ gains[i] ≤ 10,000
  • 1 ≤ target ≤ 1,000,000,000
Start with brute force

For every start, add segments until the total reaches target, and keep the smallest count.

That is up to n steps for each of n starts, which is about 50 million additions for 10,000 segments and a large target. Each start re-adds almost the same segments as the previous one.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code