【數組】B053_可獲得的最大點數(暴搜 / 前綴和 + 後綴和)

一、Problem

There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

Your score is the sum of the points of the cards you have taken.

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

Constraints:

  • 1 <= cardPoints.length <= 10^5
    1 <= cardPoints[i] <= 10^4
    1 <= k <= cardPoints.length
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. 
However, choosing the rightmost card first will maximize your total score. 
The optimal strategy is to take the three cards on the right, 
giving a final score of 1 + 6 + 5 = 12.

二、Solution

嘗試二:dfs(超時)

  • 先一直拿左邊的數,直到數組末尾。
  • 然後回退一層,拿一下右邊的數。
  • 再回退,直到做到疏而不漏…

24/40 …

int max, k, N;
int[] cs;
public int maxScore(int[] cs, int k) {
    this.k = k;
    this.cs = cs;
    N = cs.length;
    if (N == k) {
        int sum = 0;
        for (int n : cs) sum += n;
        return sum;
    }
    dfs(0, N-1, 0, 0);
    return max;
}
void dfs(int l, int r, int c, int s) {
    if (l >= N || r < 0)
        return;
    if (c == k && l <= r) {
        max = Math.max(max, s);
        return;
    }
    dfs(l+1, r, c+1, s+cs[l]);
    dfs(l, r-1, c+1, s+cs[r]);
}

複雜度分析

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

方法三:前綴和 + 後綴和

  • 最終的取法結果一定是左邊拿了 n 張,右邊拿了 m 張 (n>=0m>=0)(n>=0,m >= 0)
  • m+n=km+n = k 恆成立。
  • 所以,我們可以先預處理從前往後拿 i 張的總得分數組,以及從後往前拿 i 張的總得分的數組。
  • 然後枚舉所有情況,即:從左邊拿了 i 張,那麼只能從右邊拿到 k-i 張。(i <= k)
public int maxScore(int[] cs, int k) {
    int N = cs.length, max = 0;
    int[] pre = new int[N+1], suf = new int[N+1];
    for (int i = 1; i <= N; i++) {
        pre[i] = pre[i-1] + cs[i-1];
        suf[i] = suf[i-1] + cs[N-i];
    }
    if (k > N)  return pre[N];
    for (int i = 0; i <= k; i++) {
        max = Math.max(max, pre[i] + suf[k-i]);
    }
    return max;
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章