![]() |
VOOZH | about |
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:
Below is the implementation for the above approach:
11
Time Complexity: O(N)
Auxiliary Space: O(N)