Sum of K Subarrays With Length at Least M Problem
#3473
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3473.
You are given an integer array nums and two integers, k and m.
Return the maximum sum of k non-overlapping subarrays of nums, where each subarray has a length of at least m.
Example 1:
Input: nums = [1,2,-1,3,3,4], k = 2, m = 2
Output: 13
Explanation:
The optimal choice is:
- Subarray nums[3..5] with sum 3 + 3 + 4 = 10 (length is 3 >= m).
- Subarray nums[0..1] with sum 1 + 2 = 3 (length is 2 >= m).
The total sum is 10 + 3 = 13.
Example 2:
Input: nums = [-10,3,-1,-2], k = 4, m = 1
Output: -10
Explanation:
The optimal choice is choosing each element as a subarray. The output is (-10) + 3 + (-1) + (-2) = -10.
Constraints:
1 <= nums.length <= 2000-10^4 <= nums[i] <= 10^41 <= k <= floor(nums.length / m)1 <= m <= 3
Solution
Approach: Dynamic Programming with Prefix Sums
Let pre be the prefix sums and f[j][i] the best total using j disjoint subarrays inside the first i elements.
Either element i is unused, f[j][i-1], or a subarray ends at i and starts at some l <= i - m: f[j-1][l] + pre[i] - pre[l]. The second option is pre[i] plus the maximum of f[j-1][l] - pre[l] over l <= i - m, and that maximum can be kept as a running value while i grows, so each layer takes linear time. Only layer j - 1 is needed to build layer j.
The answer is f[k][n].
Complexity: O(nk) time, O(n) space.
class Solution:
def maxSum(self, nums: List[int], k: int, m: int) -> int:
n = len(nums)
pre = [0] * (n + 1)
for i, x in enumerate(nums):
pre[i + 1] = pre[i] + x
NEG = float("-inf")
f = [0] * (n + 1)
for j in range(1, k + 1):
g = [NEG] * (n + 1)
best = NEG
for i in range(j * m, n + 1):
best = max(best, f[i - m] - pre[i - m])
g[i] = max(g[i - 1], best + pre[i])
f = g
return f[n]