题目描述
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 :
Input: [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11
Nodes :
2 <= A.length <= 50000
1 <= A[i] <= 1000
Code
1.A[i] + A[j] + i - j = A[i] + i + A[j] - j。所以可以重新构建两个数组,分别存储A[i]+i和A[i]-i.然后计算这两个数组中元素之和的最大值。(传送门)
class Solution {
public int maxScoreSightseeingPair(int[] A) {
if (A == null || A.length <= 1) return 0;
int[] plus = new int[A.length];
int[] minus = new int[A.length];
for (int i = 0; i < A.length; i++) {
plus[i] = A[i] + i;
minus[i] = A[i] - i;
}
int p = plus[0];
int m = minus[1];
int res = Integer.MIN_VALUE;
for (int i = 1; i < A.length; i++) {
// now we search max minus from index i
m = Math.max(m, minus[i]);
res = Math.max(res, p + m);
if (plus[i] > p) {
p = plus[i];
m = Integer.MIN_VALUE;
continue;
}
}
return res;
}
}
改进一下:记录之前最大A[i]+i的id(传送门)
public int maxScoreSightseeingPair(int[] A) {
int ans =A[0];
int prevBestIdx =0;
for(int j=1;j<A.length;j++){
ans = Math.max(ans, A[prevBestIdx]+prevBestIdx+A[j]-j);
if(A[prevBestIdx ]+prevBestIdx <A[j]+j){
prevBestIdx =j;
}
}
return ans;
}
2.下面这个思路太厉害了。还是先看代码(传送门):
public int maxScoreSightseeingPair(int[] A) {
int res = 0, cur = 0;
for (int a: A) {
res = Math.max(res, cur + a);
cur = Math.max(cur, a) - 1;
}
return res;
}
解释一下,cur这个变量记录的是之前最大值减去到当前的位置。你每往前走一步,那么相当于最大值的value减去1,然后在加上当前的value,与记录的最大值比较,即得答案。