原题说明
Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning.
Example 1:
Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]
Note:
1 <= K <= A.length <= 5000 <= A[i] <= 10^6
解题思路
动态规划,用p[i]来表示A中前i个元素能够得到的最大值。
对于下一位dp[i + 1](即新加入元素A[i])来说,我们将以A[i]结尾的切分(partition)的长度从len = 1开始向前遍历,直到达到长度上限K:len = K
或者达到最左边:i - len + 1 = 0
对于每一个以A[i]结尾的切分长度len,我们首先计算该切分中的最大值(即从i到i - len + 1之间A的最大值),用max_value表示:max_value = max(max_value, A[i - len + 1]);
然后将dp[i + 1]的值更新为:max(dp[i + 1], max_value * len + dp[i - len + 1])
返回dp数组最后一个值:dp[A.size()]
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(N * K), N为数组A的长度
空间复杂度: O(N)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!