Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum Sum of two non-overlapping Subarrays of any length
Next article icon

Maximum Sum of two non-overlapping Subarrays of any length

Last Updated : 03 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++14
// C++ code for the above approach:  #include <bits/stdc++.h> using namespace std; typedef long long ll;  // Function to find the maximum sum // of two non-overlapping subarray int maxNonIntersectSum(int* A, int& N) {     vector<int> frontKadane;     vector<int> backKadane(N);     int sum1 = 0, sum2 = 0, result = 0;      frontKadane.push_back(0);     backKadane.push_back(0);      // Loop to calculate the     // maximum subarray sum till ith index     for (int i = 0; i < N; i++) {         sum1 += A[i];         sum2 = max(sum1, sum2);         sum1 = max(sum1, 0);         frontKadane.push_back(sum2);     }      sum1 = 0;     sum2 = 0;      // Loop to calculate the     // maximum subarray sum till ith index     for (int i = N - 1; i >= 0; i--) {         sum1 += A[i];         sum2 = max(sum1, sum2);         sum1 = max(sum1, 0);         backKadane[i] = sum2;     }      for (int i = 0; i <= N; i++)         result             = max(result, backKadane[i]                               + frontKadane[i]);      // Return the maximum     // non-overlapping subarray sum     return result; }  // Driver code int main() {     int A[] = { 5, -2, 3, -6, 5 };     int N = sizeof(A) / sizeof(A[0]);      // Function call     cout << maxNonIntersectSum(A, N);     return 0; } 
Java
// Java code for the above approach  import java.io.*;  class GFG {      // Function to find the maximum sum of two     // non-overlapping subarray     static int maxNonIntersect(int[] A, int N)     {          int[] frontKadane = new int[N];         int[] backKadane = new int[N];          int sum1 = 0, sum2 = 0, result = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (int i = 0; i < N; i++) {             sum1 += A[i];             sum2 = Math.max(sum1, sum2);             sum1 = Math.max(sum1, 0);             frontKadane[i] = sum2;         }          sum1 = 0;         sum2 = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (int i = N - 1; i >= 0; i--) {             sum1 += A[i];             sum2 = Math.max(sum1, sum2);             sum1 = Math.max(sum1, 0);             backKadane[i] = sum2;         }          for (int i = 0; i < N; i++) {             result = Math.max(result, backKadane[i]                                           + frontKadane[i]);         }          // Return the maximum non-overlapping subarray sum         return result;     }      public static void main(String[] args)     {          int[] A = { 5, -2, 3, -6, 5 };         int N = A.length;          // Function call         System.out.print(maxNonIntersect(A, N));     } }  // This code is contributed by lokesh (lokeshmvs21). 
Python3
# Python3 code for the above approach:  # Function to find the maximum sum # of two non-overlapping subarray   def maxNonIntersectSum(A, N):     frontKadane = []     backKadane = [0]*N     sum1 = 0     sum2 = 0     result = 0      frontKadane.append(0)     backKadane.append(0)      # Loop to calculate the     # maximum subarray sum till ith index     for i in range(N):         sum1 += A[i]         sum2 = max(sum1, sum2)         sum1 = max(sum1, 0)         frontKadane.append(sum2)      sum1 = 0     sum2 = 0      # Loop to calculate the     # maximum subarray sum till ith index     for i in range(N-1, 0, -1):         sum1 += A[i]         sum2 = max(sum1, sum2)         sum1 = max(sum1, 0)         backKadane[i] = sum2      for i in range(N+1):         result = max(result, backKadane[i] + frontKadane[i])      # Return the maximum     # non-overlapping subarray sum     return result   # Driver code if __name__ == "__main__":     A = [5, -2, 3, -6, 5]     N = len(A)     # Function call     print(maxNonIntersectSum(A, N))  # This code is contributed by Rohit Pradhan 
C#
// C# code for the above approach  using System;  public class GFG {      // Function to find the maximum sum of two     // non-overlapping subarray     static int maxNonIntersect(int[] A, int N)     {          int[] frontKadane = new int[N];         int[] backKadane = new int[N];          int sum1 = 0, sum2 = 0, result = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (int i = 0; i < N; i++) {             sum1 += A[i];             sum2 = Math.Max(sum1, sum2);             sum1 = Math.Max(sum1, 0);             frontKadane[i] = sum2;         }          sum1 = 0;         sum2 = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (int i = N - 1; i >= 0; i--) {             sum1 += A[i];             sum2 = Math.Max(sum1, sum2);             sum1 = Math.Max(sum1, 0);             backKadane[i] = sum2;         }          for (int i = 0; i < N; i++) {             result = Math.Max(result, backKadane[i]                                           + frontKadane[i]);         }          // Return the maximum non-overlapping subarray sum         return result;     }      public static void Main(string[] args)     {          int[] A = { 5, -2, 3, -6, 5 };         int N = A.Length;          // Function call         Console.Write(maxNonIntersect(A, N));     } }  // This code is contributed by AnkThon 
JavaScript
<script>     // JavaScript program for above approach:      // Function to find the maximum sum of two     // non-overlapping subarray    function maxNonletersect(A, N)     {          let frontKadane = new Array(N);         let backKadane = new Array(N);          let sum1 = 0, sum2 = 0, result = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (let i = 0; i < N; i++) {             sum1 += A[i];             sum2 = Math.max(sum1, sum2);             sum1 = Math.max(sum1, 0);             frontKadane[i] = sum2;         }          sum1 = 0;         sum2 = 0;          // Loop to calculate the maximum subarray sum till         // ith index         for (let i = N - 1; i >= 0; i--) {             sum1 += A[i];             sum2 = Math.max(sum1, sum2);             sum1 = Math.max(sum1, 0);             backKadane[i] = sum2;         }          for (let i = 0; i < N; i++) {             result = Math.max(result, backKadane[i]                                           + frontKadane[i]);         }          // Return the maximum non-overlapping subarray sum         return result;     }      // Driver Code         let A = [ 5, -2, 3, -6, 5 ];         let N = A.length;          // Function call         document.write(maxNonletersect(A, N));  // This code is contributed by code_hunt. </script> 

Output
11

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


Next Article
Maximum Sum of two non-overlapping Subarrays of any length

P

prophet1999
Improve
Article Tags :
  • Greedy
  • Competitive Programming
  • TrueGeek
  • DSA
  • Arrays
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

    Maximum sum of non-overlapping subarrays of length atmost K
    Given an integer array 'arr' of length N and an integer 'k', select some non-overlapping subarrays such that each sub-array if of length at most 'k', no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays are maximum.Examples: Input : arr[] = {-1, 2, -3, 4, 5}, k = 2 O
    10 min read
    Maximum sum two non-overlapping subarrays of given size
    Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of
    12 min read
    Maximum sum of lengths of non-overlapping subarrays with k as the max element.
    Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element. Examples: Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4} k = 4 Output : 5 {2, 1, 4} => Length = 3 {3, 4} => Length = 2 So, 3 + 2 = 5 is the answer Input : arr[] = {1, 2, 3, 2, 3, 4, 1
    15+ min read
    Max sum of M non-overlapping subarrays of size K
    Given an array and two numbers M and K. We need to find the max sum of sums of M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array si
    15+ min read
    Maximize count of non-overlapping subarrays with sum K
    Given an array arr[] and an integer K, the task is to print the maximum number of non-overlapping subarrays with a sum equal to K. Examples: Input: arr[] = {-2, 6, 6, 3, 5, 4, 1, 2, 8}, K = 10Output: 3Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences