Start learning free

LESSON 240 OF 410 · PARTIAL SUMS #2

Maximum Sum of Three Non-Overlapping Subarrays III in Python (Time Complexity: O(n))

Practice O(n2) Read the full explanation

Given an array nums of integers, find three non-overlapping subarrays with maximum sum.

Return the total sum of the three subarrays

Example:

Input: [2, 3, -8, 7, -2, 9, -9, 7, -2, 4]
Output: 28
Explanation: Subarrays [2, 3], [7, -2, 9] and [7, -2, 4]
             have the maximum sum of 28

 

Note:

  • Subarrays must be non-empty
  • nums contains at least three numbers
STEP 1 OF 22
    Ctrl + Enter to check

    PYTHON · PARTIAL SUMS #2

    Max Sum Of Three Subarrays in Python, explained

    Understanding the Problem

    The core challenge of this problem is to find three non-overlapping subarrays that together have the maximum possible sum. This problem is significant in scenarios where we need to maximize the sum of multiple segments of data, such as in financial analysis or signal processing.

    Potential pitfalls include overlapping subarrays and not considering all possible subarray combinations.

    Approach

    To solve this problem, we can break it down into manageable steps:

    1. Calculate the sum of all possible subarrays of a given length.
    2. Use dynamic programming to keep track of the best subarray sums up to each point in the array.
    3. Combine these results to find the maximum sum of three non-overlapping subarrays.

    Naive Solution

    A naive solution would involve checking all possible combinations of three subarrays, but this approach is not optimal due to its high time complexity.

    Optimized Solution

    We can optimize the solution using dynamic programming and prefix sums. The idea is to precompute the sums of all subarrays of a given length and then use these precomputed sums to find the maximum sum of three non-overlapping subarrays efficiently.

    Algorithm

    Here is a step-by-step breakdown of the optimized algorithm:

    1. Compute the prefix sums of the array to quickly calculate subarray sums.
    2. Use three arrays to store the maximum subarray sums up to each point in the array for the first, second, and third subarrays.
    3. Iterate through the array to update these arrays with the maximum sums found so far.
    4. Combine the results to find the maximum sum of three non-overlapping subarrays.

    Code Implementation

    def maxSumOfThreeSubarrays(nums, k):
        n = len(nums)
        sum_k = [0] * (n - k + 1)
        current_sum = sum(nums[:k])
        
        # Calculate the sum of each subarray of length k
        for i in range(n - k + 1):
            if i > 0:
                current_sum = current_sum - nums[i - 1] + nums[i + k - 1]
            sum_k[i] = current_sum
        
        # Arrays to store the best subarray sums up to each point
        left = [0] * (n - k + 1)
        right = [0] * (n - k + 1)
        
        # Fill the left array
        best = 0
        for i in range(n - k + 1):
            if sum_k[i] > sum_k[best]:
                best = i
            left[i] = best
        
        # Fill the right array
        best = n - k
        for i in range(n - k, -1, -1):
            if sum_k[i] >= sum_k[best]:
                best = i
            right[i] = best
        
        # Find the maximum sum of three non-overlapping subarrays
        max_sum = 0
        for j in range(k, n - 2 * k + 1):
            i, l = left[j - k], right[j + k]
            total = sum_k[i] + sum_k[j] + sum_k[l]
            if total > max_sum:
                max_sum = total
        
        return max_sum
    
    # Example usage
    nums = [2, 3, -8, 7, -2, 9, -9, 7, -2, 4]
    k = 2
    print(maxSumOfThreeSubarrays(nums, k))  # Output: 28
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the length of the input array. This is because we make a constant number of passes through the array. The space complexity is also O(n) due to the additional arrays used for storing subarray sums and indices.

    Edge Cases

    Potential edge cases include:

    • Arrays with negative numbers.
    • Arrays where the optimal subarrays are at the beginning or end of the array.

    These edge cases are handled by the algorithm as it considers all possible subarrays of the given length.

    Testing

    To test the solution comprehensively, consider the following test cases:

    # Test case 1: General case
    assert maxSumOfThreeSubarrays([2, 3, -8, 7, -2, 9, -9, 7, -2, 4], 2) == 28
    
    # Test case 2: All positive numbers
    assert maxSumOfThreeSubarrays([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) == 27
    
    # Test case 3: All negative numbers
    assert maxSumOfThreeSubarrays([-1, -2, -3, -4, -5, -6, -7, -8, -9], 2) == -12
    
    # Test case 4: Mixed positive and negative numbers
    assert maxSumOfThreeSubarrays([1, -2, 3, -4, 5, -6, 7, -8, 9], 2) == 15
    
    # Test case 5: Optimal subarrays at the beginning
    assert maxSumOfThreeSubarrays([9, 8, 7, 6, 5, 4, 3, 2, 1], 2) == 27
    

    Thinking and Problem-Solving Tips

    When approaching such problems, consider breaking them down into smaller subproblems and using dynamic programming to store intermediate results. Practice solving similar problems to develop a deeper understanding of the techniques involved.

    Conclusion

    Understanding and solving problems like the maximum sum of three non-overlapping subarrays is crucial for developing strong problem-solving skills. By breaking down the problem and using efficient algorithms, we can solve complex problems effectively.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free