Problem 220174 · medium · Level 02 Linear Data Structures

Trips Down the Mine

arrays · prefix-sums · state-tracking

A mine lift starts at ground level (altitude 0). steps lists its moves in order: a negative number takes it down that many levels, a positive one brings it up. A trip underground, here called a valley, begins when the lift goes from ground level or above to below 0, and ends when it is back at 0 or above. Return how many of those trips were completed.

Examples

Input:  steps = [-1, 1, -1, -1, 1, 1]
Output: 2
Explanation: Altitudes -1, 0, -1, -2, -1, 0 - two trips below ground, both completed.

Input:  steps = [1, -1, 1, -1]
Output: 0
Explanation: The lift only ever rises above ground and comes back.

Input:  steps = [-2, 1, 3, -1, -1, 2]
Output: 1

Constraints

  • 0 <= len(steps) <= 10**5
  • -10 <= steps[i] <= 10
  • Target: O(n) time, O(1) extra space.

Goals

  • Maintain a running altitude
  • Detect transitions across a threshold rather than the values themselves
Starting Python…