Skip to content

1063. Best Sightseeing Pair

Difficulty: Medium

LeetCode Problem View on GitHub


1063. Best Sightseeing Pair

Medium


You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.

Return the maximum score of a pair of sightseeing spots.

 

Example 1:

Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11

Example 2:

Input: values = [1,2]
Output: 2

 

Constraints:

  • 2 <= values.length <= 5 * 104
  • 1 <= values[i] <= 1000

Solution

class Solution {
    public int maxScoreSightseeingPair(int[] values) {
        int n = values.length;
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) arr[i] = values[i] - i;
        int maxi = Integer.MIN_VALUE;
        int suff_maxi[] = new int[n];
        for (int i = n - 1; i >= 0; i--) {
            maxi = Math.max(maxi, arr[i]);
            suff_maxi[i] = maxi;
        }
        int res = 0;
        for (int i = 0; i < n - 1; i++) {
            int current_sum = values[i] + i;
            current_sum += (suff_maxi[i + 1]);
            res = Math.max(res, current_sum);
        }
        return res;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here