VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-of-two-non-overlapping-subarrays-of-any-length/

⇱ Maximum Sum of two non-overlapping Subarrays of any length - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Sum of two non-overlapping Subarrays of any length

Last Updated : 23 Jul, 2025

Given an array A consisting of N integers, the task is to find the maximum sum of two non-overlapping subarrays of any length of the array.

Note: You can select empty subarrays also.

Examples: 

Input: N = 3, A[] = {-4, -5, -2}
Output: 0
Explanation: Two empty subarrays are optimal with maximum sum = 0.

Input:  N = 5, A[] = {5, -2, 3, -6, 5}
Output: 11
Explanation: Optimal subarrays are {5, -2, 3} and {5} with maximum sum = 11.

Approach: To solve the problem follow the below idea:

This problem can be thought of as the maximum sum contiguous subarray (Kadane's Algorithm) from both left and right directions. 
By applying this algorithm, we are ensuring a maximum contiguous sum up to an index that can be stored in two vectors from front and back for finding maximum non-intersecting sum.

Follow the given steps to solve the problem:

  • Initialize two vectors frontKadane and backKadane with 0.
  • Traverse array A and implement Kadane Algorithm from left to right and store the maximum subarray sum in frontKadane[i].
  • Traverse array A and implement Kadane Algorithm from right to left and store the maximum subarray sum in backKadane[i].
  • Traverse from 0 to N and calculate maximum value of (frontKadane[i] + backKadane[i]) and store in the variable result.
  • Return the result as the final answer. 

Below is the implementation for the above approach:


Output
11

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags: