Maximum Sum of Two Non-Overlapping Subarrays — LeetCode 1031 Python Solution

MediumArrayDynamic ProgrammingSliding Window
Problem
#1031
Reading time
3 min

The problem

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.

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays?
LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays is rated Medium on LeetCode.
What topics does LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays cover?
LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays is tagged Array, Dynamic Programming and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview