【線性 dp】B008_LC_最佳觀光組合(dp / 空間優化)

一、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(超時)

  • 定義狀態
    • f[i]f[i] 表示枚舉到第 ii 個景點時的最大組合值
  • 思考初始化:
    • f[0...n]=0f[0...n] = 0
  • 思考狀態轉移方程
    • 不選第 ii 個景點 f[i]=f[i1]f[i] = f[i-1]
    • 選第 ii 個景點 f[i]=a[i]+a[j](ij)f[i] = a[i]+a[j] - (i-j)
  • 思考輸出f[n1]f[n-1]
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];
    }
}

複雜度分析

  • 時間複雜度:O(n2)O(n^2)
  • 空間複雜度:O(n)O(n)

方法二:優化 dp

在方法一種,我們用了額外的 O(n)O(n) 的時間去找到區間 [0,i][0, i] 的最大旅遊值,這可以用一個數組記錄區間 [0,i)[0, i) 中的最大旅遊值,用的時候直接取即可…

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];
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

做出來就沒想那麼多了,參考空間更優的做法是,只用一個變量記錄位置 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];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章