Best Sightseeing Pair

MediumKadane-style · Running Maximum🧩 Kadane's Running BestLeetCode #1014 ↗Updated

Problem

Each spot i has an attractiveness values[i]. Visiting spots i < j scores values[i] + values[j] + i - j: their combined value minus the distance between them. Return the maximum score over all pairs.
Inputvalues = [8,1,5,2,6]Output11 (i=0, j=2: 8+5+0-2)
Inputvalues = [1,2]Output2

2 ≤ n ≤ 5·104  ·  1 ≤ values[i] ≤ 1000

Try it yourself

Java
class Solution {
    public int maxScoreSightseeingPair(int[] values) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Split the score into a left part and a right part: (values[i] + i) + (values[j] - j). For each j we only need the best values[i] + i seen so far, which a single running maximum provides.
PatternKadane's Running Best

Instinct Best sum or product of a contiguous subarray in one pass? At each index choose - extend the run ending here or restart - and track the global best.

Memory hack Carry the bag only while it helps - a negative past is dead weight, drop it and restart here.

Open the Kadane's Running Best guide →

Approaches

Brute ForceTry Every Pair

Time O(n2)Space O(1)

Evaluate the formula for every pair i < j and keep the largest score. It follows the definition directly, so it is a reliable reference for testing.

Java
public int maxScoreSightseeingPair(int[] values) {
    int best = Integer.MIN_VALUE;
    for (int i = 0; i < values.length; i++) {
        for (int j = i + 1; j < values.length; j++) {
            best = Math.max(best, values[i] + values[j] + i - j);
        }
    }
    return best;
}

About 1.25·109 pairs at the limit — too slow.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every PairO(n2)O(1)
BetterPrefix-Maximum ArrayO(n)O(n)
OptimalSingle Pass with Running MaxO(n)O(1)
Common pitfalls
  • Updating bestLeft before scoring — allows i == j.
  • Tracking the max of values[i] alone — ignores the distance penalty.
  • Initialising the answer to 0 is fine here (scores ≥ 1), but MIN_VALUE is safer in general.
Interview tips
  • Rewrite the formula into an i-only part and a j-only part first.
  • Relate it to Best Time to Buy and Sell Stock: track the best “buy” so far.
  • Walk through the prefix-array version, then show it collapses to one variable.
Pattern
Running maximum (Kadane-style) → maximise f(i) + g(j) over i < j in one pass.
My notes saved in this browser