1. 程式人生 > >689. Maximum Sum of 3 Non-Overlapping Subarrays三個不重合數組的求和最大值

689. Maximum Sum of 3 Non-Overlapping Subarrays三個不重合數組的求和最大值

題目 分鐘 為什麽 lex OS star nat fin 空間分析

[抄題]:

In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.

Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.

Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.

Example:

Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.

[暴力解法]:

時間分析:

空間分析:

[優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

把“前i項”初始化為“第i項”,方便直接做差

for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }

[思維問題]:

不知道為什麽要用DP:每次都保存之前一組的狀態,然後一個個向前更新和比價。

求一組固定為k長度的數組時可用。

//總和=本組和+之前組的和=本組最後之和-本組第一之和+之前的(從j - k開始的)dp求和值
int curSum = sums[j] - sums[j - k] + dp[i - 1][j - k];

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

dp數組裏存儲了結果,可以通過不斷輸入index來把結果取出來:

int index = n;
        for (int i = 2; i >= 0; i--) {
            res[i] = pos[i + 1][index];
            System.out.println("index = " +index);
            System.out.println("res[i] = pos[i + 1][index] = " +res[i]);
            
            index = res[i];
            System.out.println("index = " +index);
            System.out.println("----------------");
           
        }

[一句話思路]:

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

[復雜度]:Time complexity: O() Space complexity: O()

[算法思想:叠代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

[是否頭一次寫此類driver funcion的代碼] :

689. Maximum Sum of 3 Non-Overlapping Subarrays三個不重合數組的求和最大值