1014. Best Sightseeing Pair LeetCode Solution

In this guide, you will get 1014. Best Sightseeing Pair LeetCode Solution with the best time and space complexity. The solution to Best Sightseeing Pair problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Best Sightseeing Pair solution in C++
  4. Best Sightseeing Pair solution in Java
  5. Best Sightseeing Pair solution in Python
  6. Additional Resources
1014. Best Sightseeing Pair LeetCode Solution image

Problem Statement of Best Sightseeing Pair

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

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1014. Best Sightseeing Pair LeetCode Solution in C++

class Solution {
 public:
  int maxScoreSightseeingPair(vector<int>& values) {
    int ans = 0;
    int bestPrev = 0;

    for (const int value : values) {
      ans = max(ans, value + bestPrev);
      bestPrev = max(bestPrev, value) - 1;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

1014. Best Sightseeing Pair LeetCode Solution in Java

class Solution {
  public int maxScoreSightseeingPair(int[] values) {
    int ans = 0;
    int bestPrev = 0;

    for (final int value : values) {
      ans = Math.max(ans, value + bestPrev);
      bestPrev = Math.max(bestPrev, value) - 1;
    }

    return ans;
  }
}
// code provided by PROGIEZ

1014. Best Sightseeing Pair LeetCode Solution in Python

class Solution:
  def maxScoreSightseeingPair(self, values: list[int]) -> int:
    ans = 0
    bestPrev = 0

    for value in values:
      ans = max(ans, value + bestPrev)
      bestPrev = max(bestPrev, value) - 1

    return ans
# code by PROGIEZ

Additional Resources

See also  1278. Palindrome Partitioning III LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.