题目:https://leetcode.com/problems/best-sightseeing-pair/
简介:
- SightSeeing Score 计算:对于SightSeeing Spots的数组,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.
- 很简单的计算方法,理论上遍历列表就可以计算,但是在面对大数据量是O(n^2)的时间复杂度一般都会超时,所以需要尽可能地减少列表遍历地次数,最佳目标时复是O(n),所以这里就需要思考如何在单次遍历的前提下,用空间资源维护另外一个数组计算。
class Solution {
public int maxScoreSightseeingPair(int[] A) {
/*
// Time out of limit
int maxScore = 0;
int score = 0;
for(int i = 0; i < A.length; i++){
for(int j = i+1; j < A.length; j++){
score = A[i] + A[j] + i - j;
if(score > maxScore){
maxScore = score;
}
}
}
return maxScore;
*/
if(A == null || A.length <= 1){ return 0;}
// 设计两个数组分别维护从左向右和从右向左的最佳位置值
int[] leftFrom = new int[A.length];
int[] rightFrom = new int[A.length];
for(int i = 0; i < A.length - 1; i++){
if(i == 0){
leftFrom[i] = i;
}else{
if (A[i] >= A[leftFrom[i-1]] || A[leftFrom[i-1]] - A[i] < i - leftFrom[i-1]){
leftFrom[i] = i;
} else{
leftFrom[i] = leftFrom[i-1];
}
}
}
for(int i = A.length - 1; i > 0; i--){
if(i == A.length - 1){
rightFrom[i] = i;
}else{
if (A[i] >= A[rightFrom[i+1]] || A[rightFrom[i+1]] - A[i] < rightFrom[i+1] - i){
rightFrom[i] = i;
} else{
rightFrom[i] = rightFrom[i+1];
}
}
}
int result = Integer.MIN_VALUE;
for(int i = 1; i < A.length; i++){
int sum = A[leftFrom[i-1]] + A[rightFrom[i]] + leftFrom[i-1] - rightFrom[i];
result = Math.max(result, sum);
}
return result;
}
}