1014. Best Sightseeing Pair

You are given an integer array values where values[i] represents the value of the i t h i^{th} 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 < = v a l u e s . l e n g t h < = 5 ∗ 10 4 2 <= values.length <= 5 * 10^4 2<=values.length<=5104
  • 1 <= values[i] <= 1000

From: LeetCode
Link: 1014. Best Sightseeing Pair


Solution:

Ideas:

We rewrite the formula:

v a l u e s [ i ] + v a l u e s [ j ] + i − j = ( v a l u e s [ i ] + i ) + ( v a l u e s [ j ] − j ) values[i]+values[j]+i−j=(values[i]+i)+(values[j]−j) values[i]+values[j]+ij=(values[i]+i)+(values[j]j)

So while scanning j from left to right:

  • keep the best previous value of values[i] + i

  • compute current score with best + values[j] - j

  • update the answer

  • then update best

Code:
int maxScoreSightseeingPair(int* values, int valuesSize) {
    int best = values[0] + 0;   // best value of values[i] + i so far
    int ans = 0;

    for (int j = 1; j < valuesSize; j++) {
        int score = best + values[j] - j;   // (values[i] + i) + (values[j] - j)
        if (score > ans) {
            ans = score;
        }

        int candidate = values[j] + j;
        if (candidate > best) {
            best = candidate;
        }
    }

    return ans;
}
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐