Related Articles
Maximize maximum possible subarray sum of an array by swapping with elements from another array
• Last Updated : 22 Apr, 2021

Given two arrays arr[] and brr[] consisting of N and K elements respectively, the task is to find the maximum subarray sum possible from the array arr[] by swapping any element from the array arr[] with any element of the array brr[] any number of times.

Examples:

Input: N = 5, K = 4, arr[] = { 7, 2, -1, 4, 5 }, brr[] = { 1, 2, 3, 2 }
Output : 21
Explanation : Swapping arr[2] with brr[2] modifies arr[] to {7, 2, 3, 4, 5}
Maximum subarray sum of the array arr[] = 21

Input : N = 2, K = 2, arr[] = { -4, -4 }, brr[] = { 8, 8 }
Output : 16
Explanation: Swap arr[0] with brr[0] and arr[1] with brr[1] modifies arr[] to {8, 8}
Maximum sum subarray of the array arr[] = 16

Approach: The idea to solve this problem is that by swapping elements of array arr and brr, the elements within arr can also be swapped in three swaps. Below are some observations:

• If two elements in the array arr[] having indices i and j are needed to be swapped, then take any temporary element from array brr[], say at index k, and perform the following operations:
• Swap arr[i] and brr[k].
• Swap brr[k] and arr[j].
• Swap arr[i] and brr[k].
• Now elements between array arr[] and brr[] can be swapped within the array arr[] as well. Therefore, greedily arrange elements in array arr[] such that it contains all the positive integers in a continuous manner.

Follow the steps below to solve the problem:

• Store all elements of array arr[] and brr[] in another array crr[].
• Sort the array crr[]  in descending order.
• Calculate the sum till the last index (less than N) in the array crr[] which contains a positive element.
• Print the sum obtained.

Below is the implementation of the above approach.

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the maximum subarray sum``// possible by swapping elements from array``// arr[] with that from array brr[]``void` `maxSum(``int``* arr, ``int``* brr, ``int` `N, ``int` `K)``{``    ``// Stores elements from the``    ``// arrays arr[] and brr[]``    ``vector<``int``> crr;` `    ``// Store elements of array arr[]``    ``// and brr[] in the vector crr``    ``for` `(``int` `i = 0; i < N; i++) {``        ``crr.push_back(arr[i]);``    ``}``    ``for` `(``int` `i = 0; i < K; i++) {``        ``crr.push_back(brr[i]);``    ``}` `    ``// Sort the vector crr``    ``// in descending order``    ``sort(crr.begin(), crr.end(),``         ``greater<``int``>());` `    ``// Stores maximum sum``    ``int` `sum = 0;` `    ``// Calculate the sum till the last``    ``// index in crr[] which is less than``    ``// N which contains a positive element``    ``for` `(``int` `i = 0; i < N; i++) {``        ``if` `(crr[i] > 0) {``            ``sum += crr[i];``        ``}``        ``else` `{``            ``break``;``        ``}``    ``}` `    ``// Print the sum``    ``cout << sum << endl;``}` `// Driver code``int` `main()``{``    ``// Given arrays and respective lengths``    ``int` `arr[] = { 7, 2, -1, 4, 5 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``int` `brr[] = { 1, 2, 3, 2 };``    ``int` `K = ``sizeof``(brr) / ``sizeof``(brr[0]);` `    ``// Calculate maximum subarray sum``    ``maxSum(arr, brr, N, K);``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``class` `GFG``{` `  ``// Function to find the maximum subarray sum``  ``// possible by swapping elements from array``  ``// arr[] with that from array brr[]``  ``static` `void` `maxSum(``int` `arr[], ``int` `brr[], ``int` `N, ``int` `K)``  ``{` `    ``// Stores elements from the``    ``// arrays arr[] and brr[]``    ``Vector crr = ``new` `Vector();` `    ``// Store elements of array arr[]``    ``// and brr[] in the vector crr``    ``for` `(``int` `i = ``0``; i < N; i++)``    ``{``      ``crr.add(arr[i]);``    ``}``    ``for` `(``int` `i = ``0``; i < K; i++)``    ``{``      ``crr.add(brr[i]);``    ``}` `    ``// Sort the vector crr``    ``// in descending order``    ``Collections.sort(crr);``    ``Collections.reverse(crr);` `    ``// Stores maximum sum``    ``int` `sum = ``0``;` `    ``// Calculate the sum till the last``    ``// index in crr[] which is less than``    ``// N which contains a positive element``    ``for` `(``int` `i = ``0``; i < N; i++)``    ``{``      ``if` `(crr.get(i) > ``0``)``      ``{``        ``sum += crr.get(i);``      ``}``      ``else``      ``{``        ``break``;``      ``}``    ``}` `    ``// Print the sum``    ``System.out.println(sum);``  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String[] args)``  ``{` `    ``// Given arrays and respective lengths``    ``int` `arr[] = { ``7``, ``2``, -``1``, ``4``, ``5` `};``    ``int` `N = arr.length;``    ``int` `brr[] = { ``1``, ``2``, ``3``, ``2` `};``    ``int` `K = brr.length;` `    ``// Calculate maximum subarray sum``    ``maxSum(arr, brr, N, K);``  ``}``}` `// This code is contributed by divyesh072019`

## Python3

 `# Python3 program for the above approach` `# Function to find the maximum subarray sum``# possible by swapping elements from array``# arr[] with that from array brr[]``def` `maxSum(arr, brr, N, K):``    ` `    ``# Stores elements from the``    ``# arrays arr[] and brr[]``    ``crr ``=` `[]` `    ``# Store elements of array arr[]``    ``# and brr[] in the vector crr``    ``for` `i ``in` `range``(N):``        ``crr.append(arr[i])` `    ``for` `i ``in` `range``(K):``        ``crr.append(brr[i])` `    ``# Sort the vector crr``    ``# in descending order``    ``crr ``=` `sorted``(crr)[::``-``1``]` `    ``# Stores maximum sum``    ``sum` `=` `0` `    ``# Calculate the sum till the last``    ``# index in crr[] which is less than``    ``# N which contains a positive element``    ``for` `i ``in` `range``(N):``        ``if` `(crr[i] > ``0``):``            ``sum` `+``=` `crr[i]``        ``else``:``            ``break` `    ``# Print the sum``    ``print``(``sum``)` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Given arrays and respective lengths``    ``arr ``=` `[ ``7``, ``2``, ``-``1``, ``4``, ``5` `]``    ``N ``=` `len``(arr)``    ``brr ``=` `[ ``1``, ``2``, ``3``, ``2` `]``    ``K ``=` `len``(brr)` `    ``# Calculate maximum subarray sum``    ``maxSum(arr, brr, N, K)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{``    ` `// Function to find the maximum subarray sum``// possible by swapping elements from array``// arr[] with that from array brr[]``static` `void` `maxSum(``int``[] arr, ``int``[] brr,``                   ``int` `N, ``int` `K)``{``    ` `    ``// Stores elements from the``    ``// arrays arr[] and brr[]``    ``List<``int``> crr = ``new` `List<``int``>();`` ` `    ``// Store elements of array arr[]``    ``// and brr[] in the vector crr``    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ``crr.Add(arr[i]);``    ``}``    ``for``(``int` `i = 0; i < K; i++)``    ``{``        ``crr.Add(brr[i]);``    ``}`` ` `    ``// Sort the vector crr``    ``// in descending order``    ``crr.Sort();``    ``crr.Reverse();`` ` `    ``// Stores maximum sum``    ``int` `sum = 0;`` ` `    ``// Calculate the sum till the last``    ``// index in crr[] which is less than``    ``// N which contains a positive element``    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ``if` `(crr[i] > 0)``        ``{``            ``sum += crr[i];``        ``}``        ``else``        ``{``            ``break``;``        ``}``    ``}`` ` `    ``// Print the sum``    ``Console.WriteLine(sum);``}` `// Driver Code``static` `void` `Main()``{``    ` `    ``// Given arrays and respective lengths``    ``int``[] arr = { 7, 2, -1, 4, 5 };``    ``int` `N = arr.Length;``    ``int``[] brr = { 1, 2, 3, 2 };``    ``int` `K = brr.Length;``    ` `    ``// Calculate maximum subarray sum``    ``maxSum(arr, brr, N, K);``}``}` `// This code is contributed by divyeshrabadiya07`

## Javascript

 ``
Output:
`21`

Time Complexity: O((N+K)*log(N+K))
Auxiliary Space: O(N+K)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up