#689

Maximum Sum of 3 Non-Overlapping Subarrays

Hard
ArrayDynamic ProgrammingSliding WindowPrefix SumDynamic ProgrammingPrefix SumSliding 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 solution uses a combination of prefix sums and dynamic programming to efficiently calculate the maximum sum of three non-overlapping subarrays. This reduces the number of calculations significantly by leveraging previously computed results.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the prefix sums for the array to quickly get the sum of any subarray.
  2. 2Step 2: Create an array to store the maximum sums of subarrays of length k up to each index.
  3. 3Step 3: Iterate through the array to find the best starting indices for the second and third subarrays while ensuring they do not overlap with the first.
  4. 4Step 4: Keep track of the maximum sum and the corresponding starting indices.
solution.py17 lines
1def maxSumOfThreeSubarrays(nums, k):
2    n = len(nums)
3    prefix_sum = [0] * (n + 1)
4    for i in range(n):
5        prefix_sum[i + 1] = prefix_sum[i] + nums[i]
6    max_sum = [0] * (n + 1)
7    for i in range(n - k + 1):
8        max_sum[i + 1] = max(max_sum[i], prefix_sum[i + k] - prefix_sum[i])
9    max_total = 0
10    result = []
11    for j in range(2 * k, n + 1):
12        for i in range(j - k):
13            total = max_sum[i + 1] + (prefix_sum[j] - prefix_sum[j - k]) + (prefix_sum[n] - prefix_sum[n - k])
14            if total > max_total:
15                max_total = total
16                result = [i, j - k, n - k]
17    return result

Complexity note: The time complexity is O(n) because we only iterate through the array a few times, and the space complexity is O(n) due to the prefix sum and max sum arrays.

  • 1Using prefix sums allows for quick calculation of subarray sums, reducing redundant calculations.
  • 2Dynamic programming helps in storing intermediate results, allowing for efficient retrieval.

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