Problem 306441 · medium · Phase 03 Linear Management & Searching

Longest Stretch With a Given Net Climb

prefix sums · hash map · first occurrence

A hiking trail is described by changes, the elevation change on each segment (positive uphill, negative downhill). Return the length (number of segments) of the longest contiguous stretch whose net elevation change is exactly k, or 0 if no stretch has that net change.

Examples

Input:  changes = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation: segments 0..3 have net change 1 - 1 + 5 - 2 = 3; no longer stretch does.

Input:  changes = [2, 2], k = 5
Output: 0

Input:  changes = [-2, -1, 2, 1], k = 1
Output: 2
Explanation: [-1, 2] has net change 1.

Constraints

  • 1 <= len(changes) <= 10**5
  • -1000 <= changes[i] <= 1000, -10**8 <= k <= 10**8
  • Target complexity: O(n) time. Checking all stretches is too slow for the largest tests.

Goals

  • Turn 'sum equals k' into a lookup of an earlier prefix value
  • Store first occurrences to maximise the stretch length
Starting Python…