Maps app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1696monotonic-deque
A hiking app lays a trail out as checkpoints in order. Each checkpoint has points: a viewpoint gives a positive number and a steep climb gives a negative one.
You start at the first checkpoint and must finish at the last. From a checkpoint you may jump ahead to any of the next jump checkpoints. Your score is the total of the points of every checkpoint you land on, the first and the last included. A trail can have 200,000 checkpoints and jump can be 100,000.
Write best_route_score(points, jump).
points[i] is the score of checkpoint i. It can be negative.jump checkpoints.points over the checkpoints it lands on, including the first and the last.int, so return a 64-bit number. A trail with one checkpoint scores that checkpoint.Input: points = [3, -6, 5, -2, 4, 1], jump = 2
Output: 13Let best[i] be the best score of a route that ends at checkpoint i. A queue of positions keeps the best totals falling from front to back, so its front is the best place to jump from.
| Checkpoint | Points | Best score | Queue of positions after adding it |
|---|---|---|---|
| 0 | 3 | 3 | 0 |
| 1 | -6 | -3 (from 0) | 0, 1 |
| 2 | 5 | 8 (from 0) | 2 |
| 3 | -2 | 6 (from 2) | 2, 3 |
| 4 | 4 | 12 (from 2) | 4 |
| 5 | 1 | 13 (from 4) | 5 |
The route 0, 2, 4, 5 scores 3 + 5 + 4 + 1 = 13.
Input: points = [7], jump = 1
Output: 7One checkpoint: the start is also the end.
Input: points = [2, -5, -5, -5, 9], jump = 4
Output: 11A jump of 4 goes straight from the first checkpoint to the last, over three steep climbs.
1 ≤ length of points ≤ 2 × 10^5, and -10^4 ≤ points[i] ≤ 10^41 ≤ jump ≤ 2 × 10^5Looking back over up to jump earlier checkpoints at every checkpoint costs close to n × jump steps. For n = 200,000 and jump = 100,000, that is about 1.5 × 10^10 steps.
The best earlier total in a sliding window is the front of a monotonic deque. Each checkpoint joins once and leaves at most once, so the pass is O(n). Scores add up to 2 × 10^9 in size, which is close to the limit of an int, so the total is a 64-bit number.