Best Sightseeing Pair

medium array dp

Problem

For indices i < j, the sightseeing pair score is values[i] + values[j] + i − j. Return the maximum score.

Inputvalues = [8,1,5,2,6]
Output11
Track best = max(values[i] + i) for i < j; for each j compute best + values[j] − j.

def maxScoreSightseeingPair(values):
    best = 0
    ans = 0
    for j, v in enumerate(values):
        ans = max(ans, best + v - j)
        best = max(best, v + j)
    return ans
function maxScoreSightseeingPair(values) {
  let best = 0, ans = 0;
  for (let j = 0; j < values.length; j++) {
    ans = Math.max(ans, best + values[j] - j);
    best = Math.max(best, values[j] + j);
  }
  return ans;
}
class Solution {
    public int maxScoreSightseeingPair(int[] values) {
        int best = 0, ans = 0;
        for (int j = 0; j < values.length; j++) {
            ans = Math.max(ans, best + values[j] - j);
            best = Math.max(best, values[j] + j);
        }
        return ans;
    }
}
int maxScoreSightseeingPair(vector<int>& values) {
    int best = 0, ans = 0;
    for (int j = 0; j < (int)values.size(); j++) {
        ans = max(ans, best + values[j] - j);
        best = max(best, values[j] + j);
    }
    return ans;
}
Time: O(n) Space: O(1)