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[i] + A[j] + i - j的最大值,可以试着稍微转变一下,实际求的是A[i] + i + A[j] - j的最大值。A[i] + i的部分,可以把他视作一个整体,只要找这个整体的最大值就好了;但是对于这个部分,A[j] - j,因为题目要求 i 要小于 j,所以j的范围只能从 1 开始,可以在得到当前 A[i] + i 的最大值之后,再累加上去,看看整体的最大值是多少。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int maxScoreSightseeingPair(int[] values) { 3 int res = 0; 4 int max = values[0] + 0; 5 for (int j = 1; j < values.length; j++) { 6 res = Math.max(res, max + values[j] - j); 7 max = Math.max(max, values[j] + j); 8 } 9 return res; 10 } 11 }