LeetCode 题解工作台
分隔数组以得到最大和
给你一个整数数组 arr ,请你将该数组分隔为长度 最多 为 k 的一些(连续)子数组。分隔完成后,每个子数组的中的所有值都会变为该子数组中的最大值。 返回将数组分隔变换后能够得到的元素最大和。本题所用到的测试用例会确保答案是一个 32 位整数。 示例 1: 输入: arr = [1,15,7,9,…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示将数组的前 个元素分隔成若干个子数组,最终的最大元素和。初始时 ,答案为 。 我们考虑如何计算 ,其中 $i \geq 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 arr,请你将该数组分隔为长度 最多 为 k 的一些(连续)子数组。分隔完成后,每个子数组的中的所有值都会变为该子数组中的最大值。
返回将数组分隔变换后能够得到的元素最大和。本题所用到的测试用例会确保答案是一个 32 位整数。
示例 1:
输入:arr = [1,15,7,9,2,5,10], k = 3 输出:84 解释:数组变为 [15,15,15,9,10,10,10]
示例 2:
输入:arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 输出:83
示例 3:
输入:arr = [1], k = 1 输出:1
提示:
1 <= arr.length <= 5000 <= arr[i] <= 1091 <= k <= arr.length
解题思路
方法一:动态规划
我们定义 表示将数组的前 个元素分隔成若干个子数组,最终的最大元素和。初始时 ,答案为 。
我们考虑如何计算 ,其中 。
对于 ,它的最后一个元素是 。由于每个子数组的长度最多为 ,并且我们需要求得子数组中的最大值,因此,我们可以从右往左枚举最后一个子数组的第一个元素 ,其中 ,过程中维护一个变量 ,表示最后一个子数组中的最大值,那么状态转移方程为:
最终的答案即为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
f = [0] * (n + 1)
for i in range(1, n + 1):
mx = 0
for j in range(i, max(0, i - k), -1):
mx = max(mx, arr[j - 1])
f[i] = max(f[i], f[j - 1] + mx * (i - j + 1))
return f[n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N*K) because each element considers up to k previous subarray lengths. Space complexity is O(N) to store dp values for all positions. This handles array sizes up to 500 efficiently without unnecessary recomputation. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Focus on defining dp[i] correctly and explaining why previous dp values are reused.
- question_mark
Expect reasoning about how subarray length limits (k) influence state transitions.
- question_mark
Look for explanation of why maximum value in each partition maximizes the sum.
常见陷阱
外企场景- error
Confusing subarray length with number of partitions leads to incorrect dp indices.
- error
Failing to update maximum within each subarray for the current length.
- error
Using nested loops incorrectly, causing O(N^2) when k is large, instead of O(N*K).
进阶变体
外企场景- arrow_right_alt
Change the problem to minimize sum by using subarray minimums instead of maximums.
- arrow_right_alt
Allow non-contiguous partitions, requiring different DP or greedy strategies.
- arrow_right_alt
Add a constraint on the number of partitions, combining partition count with sum maximization.