原题说明
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.
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
解题思路
遍历数组A
,我们用max_score
来记录当前最大的分数,用pre_max
来记录当前元素之前最高的分数
每遍历一个元素a
,我们首先更新max_score
: max_score = max(max_score, a + pre_max)
然后更新pre_max
: pre_max = max(pre_max, a) - 1
这里-1
是因为每往后一个元素,距离会增加1
示例代码 (cpp)
1 | class Solution { |
示例代码(java)
1 | class Solution { |
示例代码(python)
1 | class Solution(object): |
复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!