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
1.思考
- 又是一开始就想到用暴力搜索,后来仔细一想就觉得不对;
- 然后开始研究A[i] + A[j] + i - j这个算是算式,就想到用A1、A2两个vector来分别存放A[i]+i、A[i]-i;
- 接着计算A1[i]+max(A2[i+1...len]),因为要一直用到max_element()这个函数,所以干脆就提前算好,A2[i]为从i到len-1的A2中最大的数;
- 最后直接用A1[i]+A2[i+1],然后求出最大值。
eg.
index 0 1 2 3 4
A 8 1 5 2 6
A1 8 2 7 5 6
(A2 8 0 3 -1 2)
A2 8 3 3 2 2
res 11 5 9 7 -
2.知识点
- *max_element()是直接返回最大值;
- *max_element()是返回最大值的位置,再减去A.begin()就得到index。
3.实现
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& A) {
int len = A.size();
vector<int> A1, A2, score;
for(int i=0; i<len; i++){
A1.push_back(A[i]+i);
A2.push_back(A[i]-i);
}
int d = *min_element(A2.begin(), A2.end());
for(int i=len-1; i>=0; i--){
d = A2[i]>d?A2[i]:d;
A2[i] = d;
}
for(int i=0; i<len-1; i++){
score.push_back(A1[i] + A2[i+1]);
}
int res = *max_element(score.begin(), score.end());
return res;
}
};