Maximize maximum possible subarray sum of an array by swapping with elements from another array

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[] = 21Input : 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 <bits/stdc++.h>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 codeint 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 approachimport 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<Integer> crr = new Vector<Integer>(); Â
    // 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 codeif __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 approachusing 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 Codestatic 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
<script>Â
    // Javascript program for the above approach         // Function to find the maximum subarray sum    // possible by swapping elements from array    // arr[] with that from array brr[]    function maxSum(arr, brr, N, K)    {Â
        // Stores elements from the        // arrays arr[] and brr[]        let crr = [];Â
        // Store elements of array arr[]        // and brr[] in the vector crr        for(let i = 0; i < N; i++)        {            crr.push(arr[i]);        }        for(let i = 0; i < K; i++)        {            crr.push(brr[i]);        }Â
        // Sort the vector crr        // in descending order        crr.sort(function(a, b){return a - b});        crr.reverse();Â
        // Stores maximum sum        let sum = 0;Â
        // Calculate the sum till the last        // index in crr[] which is less than        // N which contains a positive element        for(let i = 0; i < N; i++)        {            if (crr[i] > 0)            {                sum += crr[i];            }            else            {                break;            }        }Â
        // Print the sum        document.write(sum);    }         // Given arrays and respective lengths    let arr = [ 7, 2, -1, 4, 5 ];    let N = arr.length;    let brr = [ 1, 2, 3, 2 ];    let K = brr.length;          // Calculate maximum subarray sum    maxSum(arr, brr, N, K);Â
</script> |
21
Â
Time Complexity: O((N+K)*log(N+K))
Auxiliary Space: O(N+K)Â
Â
Â
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



