Description
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.
The score of a pair (i < j) of sightseeing spots is (A[i] + A[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.
给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。
一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。
返回一对观光景点能取得的最高分。
题目链接:https://leetcode.com/problems/best-sightseeing-pair/
Difficulty: medium
Example 1:
Input: [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11
Note:
- 2 <= A.length <= 50000
- 1 <= A[i] <= 1000
分析
- 两次遍历,计算两点评分之后,找到最大,这样做时间复杂度为 $O(N^2)$,时间会超限;
- 用cur记录当前最大分数,max(cur,a),向后遍历距离加一,再减一;
- 用res记录到当前位置的最大值,max(res,cur+a),cur已经把距离都已经减掉了;
- 返回res。
参考代码
def maxScoreSightseeingPair(self, A):
    cur = res = 0
    for a in A:
        res = max(res, cur + a)
        cur = max(cur, a) - 1
    return res