Maximum Sum of M Non-Overlapping Subarrays II Problem
Description
LeetCode Problem 3957.
You are given an integer array nums of length n, and three integers m, l, and r.
Your task is to select at least one and at most m non-overlapping subarrays from nums such that:
- Each selected subarray has a length between
[l, r](inclusive). - The total sum of all selected subarrays is maximized.
Return the maximum total sum you can achieve.
Example 1:
Input: nums = [4,1,-5,2], m = 2, l = 1, r = 3
Output: 7
Explanation:
One optimal strategy is to:
- Select the subarray [4, 1] with sum 4 + 1 = 5 and the subarray [2] with sum 2. Both subarrays have length between [l, r].
- The total sum of these subarrays is 5 + 2 = 7, which is the maximum achievable sum with at most m = 2 subarrays.
Example 2:
Input: nums = [1,0,3,4], m = 2, l = 1, r = 2
Output: 8
Explanation:
One optimal strategy is to:
- Select the subarray [1] with sum 1 and the subarray [3, 4] with sum 3 + 4 = 7. Both subarrays have length between [l, r].
- The total sum of these subarrays is 1 + 7 = 8, which is the maximum achievable sum with at most m = 2 subarrays.
Example 3:
Input: nums = [-1,7,-4], m = 1, l = 2, r = 3
Output: 6
Explanation:
- Select the subarray [-1, 7] from nums which has length between [l, r].
- The total sum of this subarray is -1 + 7 = 6, which is the maximum achievable sum with at most m = 1 subarray.
Example 4:
Input: nums = [-3,-4,-1], m = 2, l = 1, r = 2
Output: -1
Explanation:
- All subarrays of nums have negative sums. The optimal strategy is to select the subarray [-1], which has length between [l, r].
- The total sum of this subarray is -1, which is the maximum achievable sum with at most m = 2 subarrays.
Constraints:
1 <= n == nums.length <= 10^5-10^5 <= nums[i] <= 10^51 <= m <= n1 <= l <= r <= n
Solution
Approach: Lagrangian Relaxation (Aliens Trick) with a Monotonic Queue
Let f(k) be the best total using exactly k valid subarrays. Choosing k disjoint intervals from a family of intervals is a min-cost-flow problem, so f is concave in k.
First find the best single subarray best1 (a sliding-window minimum over prefix sums). If best1 <= 0, every subarray is non-positive and, by concavity, one subarray is optimal, so return best1. Otherwise f(1) > 0 and the "at least one" rule does not matter.
Now handle the "at most m" limit by giving every subarray a penalty lam. For a fixed lam, a linear DP computes the best penalized value and, among ties, the fewest subarrays used: dp[i] = max(dp[i - 1], max over t in [i - r, i - l] of dp[t] + pre[i] - pre[t] - lam), where the inner maximum comes from a monotonic queue. The count of subarrays decreases as lam grows, and slopes of f are integers between 0 and best1. Binary search the smallest integer lam whose count is at most m; the answer is value + lam * m.
Complexity: time O(n log S) where S is the largest possible single-subarray sum, space O(n).
class Solution:
def maximumSum(self, nums: List[int], m: int, l: int, r: int) -> int:
n = len(nums)
pre = [0] * (n + 1)
for i, x in enumerate(nums):
pre[i + 1] = pre[i] + x
# Best value and fewest subarrays when every chosen subarray costs lam.
def solve(lam: int):
dpv = [0] * (n + 1)
dpc = [0] * (n + 1)
qi = [0] * (n + 1)
qv = [0] * (n + 1)
qc = [0] * (n + 1)
head = tail = 0
for i in range(1, n + 1):
t = i - l
if t >= 0:
v, c = dpv[t] - pre[t], dpc[t]
while tail > head and (qv[tail - 1] < v or (qv[tail - 1] == v and qc[tail - 1] >= c)):
tail -= 1
qi[tail], qv[tail], qc[tail] = t, v, c
tail += 1
while head < tail and qi[head] < i - r:
head += 1
dpv[i], dpc[i] = dpv[i - 1], dpc[i - 1]
if head < tail:
cv, cc = qv[head] + pre[i] - lam, qc[head] + 1
if cv > dpv[i] or (cv == dpv[i] and cc < dpc[i]):
dpv[i], dpc[i] = cv, cc
return dpv[n], dpc[n]
# best single subarray
best1 = None
qi = [0] * (n + 1)
head = tail = 0
for i in range(l, n + 1):
t = i - l
while tail > head and pre[qi[tail - 1]] >= pre[t]:
tail -= 1
qi[tail] = t
tail += 1
while qi[head] < i - r:
head += 1
cand = pre[i] - pre[qi[head]]
if best1 is None or cand > best1:
best1 = cand
if best1 <= 0:
return best1
lo, hi = 0, best1
while lo < hi:
mid = (lo + hi) // 2
if solve(mid)[1] <= m:
hi = mid
else:
lo = mid + 1
return solve(lo)[0] + lo * m