progress

~/problems / Arrays & hashing / Prefix sums and difference arrays

Uphill metres between checkpoints

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A trail has checkpoints 0..n-1 with elevations heights[i]. Hikers walk in either direction, and their fitness app counts only climbing: each step up adds the height difference, each step down adds nothing.

Write uphill(heights: list[int], trips: list[tuple[int, int]]) -> list[int] that returns the metres climbed on each trip (a, b).

uphill([100, 130, 120, 160, 150], [(0, 4), (4, 0), (1, 3), (2, 2)])   # [70, 20, 40, 0]
uphill([5, 5, 5], [(0, 2), (2, 0)])                                     # [0, 0]

(4 -> 0 climbs 150 -> 160 and 120 -> 130: 20 metres.)

Up to 10^5 checkpoints and trips; elevations in [-10^9, 10^9].

⭐ Bonus: a speed test with 10^5 trips earns a star at O(1) per trip.

Show hint

keep two prefix arrays, rises and drops. A forward trip reads the rises; a backward trip reads the drops (a drop walked backwards is a climb).

Topic: Prefix sums and difference arrays. O(1) range sums (1D and 2D); O(1) range updates with difference arrays.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc