一、Problem
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.
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
二、Solution
方法一:dp(超時)
- 定義狀態:
- 表示枚舉到第 個景點時的最大組合值
- 思考初始化:
- 思考狀態轉移方程:
- 不選第 個景點
- 選第 個景點
- 思考輸出:
class Solution {
public int maxScoreSightseeingPair(int[] a) {
int n = a.length, f[] = new int[n];
for (int i = 1; i < n; i++) {
f[i] = f[i-1]; // 不選第i個景點
for (int j = 0; j < i; j++) //選上第i個景點
f[i] = Math.max(f[i], a[i]+a[j] - (i-j));
}
return f[n-1];
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:優化 dp
在方法一種,我們用了額外的 的時間去找到區間 的最大旅遊值,這可以用一個數組記錄區間 中的最大旅遊值,用的時候直接取即可…
class Solution {
public int maxScoreSightseeingPair(int[] a) {
int n = a.length, g[] = new int[n], f[] = new int[n];
g[0] = a[0]; // a[0]+0
for (int i = 1; i < n; i++)
g[i] = Math.max(g[i-1], a[i] + i);
for (int i = 1; i < n; i++) {
f[i] = Math.max(f[i-1], g[i-1] + a[i] - i);
}
return f[n-1];
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
做出來就沒想那麼多了,參考空間更優的做法是,只用一個變量記錄位置 i 之前的最大值即可。
方法三:空間優化
class Solution {
public int maxScoreSightseeingPair(int[] a) {
int n = a.length, g = a[0], f[] = new int[n];
for (int i = 1; i < n; i++) {
f[i] = Math.max(f[i-1], g + a[i] - i);
g = Math.max(g, a[i] + i);
}
return f[n-1];
}
}