class Solution:
def maximumSum(self, nums: List[int], m: int, l: int, r: int) -> int:
n = len(nums)
NEG_INF = float('-inf')
# pf[i] = sum of nums[0..i], inclusive
pf = [0] * n
pf[0] = nums[0]
for i in range(1, n):
pf[i] = pf[i - 1] + nums[i]
def prefix_sum(idx):
# sum of nums[0..idx-1] -- i.e. everything strictly before idx
if idx == 0:
return 0
return pf[idx - 1]
dp = [[NEG_INF] * (n + 1) for _ in range(m + 1)]
for i in range(n + 1):
dp[0][i] = 0
for j in range(1, m + 1):
window = deque() # holds (idx, g_value), g decreasing front-to-back
for i in range(n + 1):
candidate_idx = i - l
if candidate_idx >= 0 and dp[j - 1][candidate_idx] != NEG_INF:
g_value = dp[j - 1][candidate_idx] - prefix_sum(candidate_idx)
while window and window[-1][1] <= g_value:
window.pop()
window.append((candidate_idx, g_value))
while window and window[0][0] < i - r:
window.popleft()
best = dp[j][i - 1] if i >= 1 else NEG_INF
if window:
candidate_value = prefix_sum(i) + window[0][1]
if candidate_value > best:
best = candidate_value
dp[j][i] = best
return max(dp[j][n] for j in range(1, m + 1))