Leetcode #1031: Maximum Sum of Two Non-Overlapping Subarrays
In this guide, we solve Leetcode #1031 Maximum Sum of Two Non-Overlapping Subarrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Dynamic Programming, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Python Solution
class Solution:
def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:
n = len(nums)
s = list(accumulate(nums, initial=0))
ans = t = 0
i = firstLen
while i + secondLen - 1 < n:
t = max(t, s[i] - s[i - firstLen])
ans = max(ans, t + s[i + secondLen] - s[i])
i += 1
t = 0
i = secondLen
while i + firstLen - 1 < n:
t = max(t, s[i] - s[i - secondLen])
ans = max(ans, t + s[i + firstLen] - s[i])
i += 1
return ans
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.