Shortest Steep Climb

Mediumsliding windowAlso known as Minimum Size Subarray Sum

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

For today's drill, a rider must climb at least target metres without stopping, over as few segments as possible. The coach wants the shortest unbroken stretch of road 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, just short. The three segments 3 to 5 climb 20 + 40 + 50 = 110, and segments 0 to 2 climb exactly 100, which counts. No two neighbouring segments reach 100 (the largest pair is 90), so the answer is 3.

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

The whole road only climbs 15 metres. No stretch reaches 20, so return 0.

Constraints

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

For every starting segment, add segments one by one until the total reaches target, and record how many it took. Keep the smallest count.

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

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