#1031

Maximum Sum of Two Non-Overlapping Subarrays

Medium
ArrayDynamic ProgrammingSliding WindowPrefix SumsDynamic ProgrammingSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses prefix sums to efficiently calculate the maximum sums of the two non-overlapping subarrays. By maintaining the maximum sum of one subarray while iterating through the array, we can find the best combination without redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a prefix sum array to quickly calculate the sum of any subarray.
  2. 2Step 2: Iterate through the array, maintaining the maximum sum of the first subarray seen so far while calculating the sum of the second subarray.
  3. 3Step 3: For each position, calculate the maximum possible sum of the two subarrays considering their lengths and update the result.
solution.py14 lines
1# Full working Python code
2
3def maxSumTwoNoOverlap(nums, firstLen, secondLen):
4    n = len(nums)
5    prefix = [0] * (n + 1)
6    for i in range(n):
7        prefix[i + 1] = prefix[i] + nums[i]
8    max_first = 0
9    max_sum = 0
10    for i in range(firstLen + secondLen - 1, n):
11        max_first = max(max_first, prefix[i - secondLen + 1] - prefix[i - secondLen + 1 - firstLen])
12        current_sum = prefix[i + 1] - prefix[i + 1 - secondLen]
13        max_sum = max(max_sum, max_first + current_sum)
14    return max_sum

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (once for prefix sums and once for calculating the maximum sums), making it efficient.

  • 1Using prefix sums allows for quick calculations of subarray sums, making the solution efficient.
  • 2Maintaining a running maximum of one subarray while iterating for the other prevents redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.