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 * 1041 <= values[i] <= 1000This approach iterates through each index in the array as a starting point and computes the score for every subsequent point. It keeps track of the maximum score found.
Although simple, this approach involves nested iteration, making it inefficient for large inputs due to the O(n^2) time complexity.
The solution uses a nested loop to brute-force calculate the score for each pair of sights (i < j). The outer loop fixes 'i' while the inner loop iterates over 'j', calculates the respective score, and updates the maximum score found.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2) due to the nested loops.
Space Complexity: O(1) as no additional space is used.
This approach is a much more efficient O(n) solution. It maintains a running maximal value of 'values[i] + i' to maximize the score of subsequent elements. As the array is traversed, it calculates and continuously updates the maximum possible score using this running maximum and 'values[j] - j'.
This optimized C solution iterates through the array, maintaining the maximal 'values[i] + i' seen so far and computing the current potential maximum score with 'values[j] - j'. The highest score is updated dynamically.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) since it makes a single pass.
Space Complexity: O(1) because additional space isn't used.
| Approach | Complexity |
|---|---|
| Approach 1: Brute Force Approach | Time Complexity: O(n^2) due to the nested loops. |
| Approach 2: Optimized Single Pass | Time Complexity: O(n) since it makes a single pass. |
Best Sightseeing Pair - Leetcode 1014 - Python • NeetCodeIO • 9,069 views views
Watch 9 more video solutions →Practice Best Sightseeing Pair with our built-in code editor and test cases.
Practice on FleetCode