Problem 275158 · hard · Phase 02 Linear Data Structures

Two Lookouts on the Ridge Trail

arrays · best-so-far · algebraic rearrangement · tie-breaking

Markers along a ridge trail are one kilometre apart; views[k] rates the view at marker k. A hiker plans two lookout stops at markers i < j that are at least min_gap kilometres apart (j - i >= min_gap). The trip scores views[i] + views[j] - (j - i): both views, minus one point per kilometre walked between them.

Return [score, i, j] for the best trip. If several trips tie on the score, pick the one with the smallest i, and among those the smallest j. If no pair of markers is far enough apart, return None.

Examples

Input:  views = [8, 1, 5, 2, 6], min_gap = 1
Output: [11, 0, 2]
Explanation: 8 + 5 - 2 = 11. The trip 0 -> 4 scores 8 + 6 - 4 = 10.

Input:  views = [3, 9, 1, 9], min_gap = 2
Output: [16, 1, 3]
Explanation: 0 -> 2 scores 2, 0 -> 3 scores 9 and 1 -> 3 scores 9 + 9 - 2 = 16.

Input:  views = [5, 5, 5, 5], min_gap = 1
Output: [9, 0, 1]
Explanation: every neighbouring pair scores 9; the tie-break picks i = 0, then j = 1.

Input:  views = [4], min_gap = 1
Output: None

Constraints

  • 0 <= len(views) <= 10**5
  • 1 <= min_gap <= 10**5
  • -10**6 <= views[k] <= 10**6
  • Target: O(n) time. Scoring every pair is far too slow for the largest tests.

Goals

  • Split a pair score into a part for each end
  • Carry the best earlier candidate with a lag
  • Apply a two-level tie-break without a nested loop
Starting Python…