Maximum possible sub-array sum after at most X swaps
Last Updated :
15 Sep, 2022
Given an array arr[] of N integers and an integer X, the task is to find the maximum possible sub-array sum after applying at most X swaps.
Examples:
Input: arr[] = {5, -1, 2, 3, 4, -2, 5}, X = 2
Output: 19
Swap (arr[0], arr[1]) and (arr[5], arr[6]).
Now, the maximum sub-array sum will be (5 + 2 + 3 + 4 + 5) = 19
Input: arr[] = {-2, -3, -1, -10}, X = 10
Output: -1
Approach: For every possible sub-array, consider the elements which are not part of this sub-array as discarded. Now, while there are swaps left and the sum of the sub-array currently under consideration can be maximized i.e. the greatest element among the discarded elements can be swapped with the minimum element of the sub-array, keep updating the sum of the sub-array. When there are no swaps left or the sub-array sum cannot be further maximized, update the current maximum sub-array sum found so far which will be the required answer in the end.
Below is the implementation of the above approach:
CPP
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum
// sub-array sum after at most x swaps
int SubarraySum(int a[], int n, int x)
{
// To store the required answer
int ans = -10000;
// For all possible intervals
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// Keep current ans as zero
int curans = 0;
// To store the integers which are
// not part of the sub-array
// currently under consideration
priority_queue<int, vector<int> > pq;
// To store elements which are
// part of the sub-array
// currently under consideration
priority_queue<int, vector<int>, greater<int> > pq2;
// Create two sets
for (int k = 0; k < n; k++) {
if (k >= i && k <= j) {
curans += a[k];
pq2.push(a[k]);
}
else
pq.push(a[k]);
}
ans = max(ans, curans);
// Swap at most X elements
for (int k = 1; k <= x; k++) {
if (pq.empty() || pq2.empty()
|| pq2.top() >= pq.top())
break;
// Remove the minimum of
// the taken elements
curans -= pq2.top();
pq2.pop();
// Add maximum of the
// discarded elements
curans += pq.top();
pq.pop();
// Update the answer
ans = max(ans, curans);
}
}
}
// Return the maximized sub-array sum
return ans;
}
// Driver code
int main()
{
int a[] = { 5, -1, 2, 3, 4, -2, 5 }, x = 2;
int n = sizeof(a) / sizeof(a[0]);
cout << SubarraySum(a, n, x);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to return the maximum
// sub-array sum after at most x swaps
static int SubarraySum(int[] a, int n, int x)
{
// To store the required answer
int ans = -10000;
// For all possible intervals
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
// Keep current ans as zero
int curans = 0;
// To store the integers which are
// not part of the sub-array
// currently under consideration
ArrayList<Integer> pq = new ArrayList<Integer>();
// To store elements which are
// part of the sub-array
// currently under consideration
ArrayList<Integer> pq2 = new ArrayList<Integer>();
// Create two sets
for (int k = 0; k < n; k++) {
if (k >= i && k <= j) {
curans += a[k];
pq2.add(a[k]);
}
else
pq.add(a[k]);
}
Collections.sort(pq);
Collections.reverse(pq);
Collections.sort(pq2);
ans = Math.max(ans, curans);
// Swap at most X elements
for (int k = 1; k <= x; k++) {
if (pq.size() == 0 || pq2.size() == 0
|| pq2.get(0) >= pq.get(0))
break;
// Remove the minimum of
// the taken elements
curans -= pq2.get(0);
pq2.remove(0);
// Add maximum of the
// discarded elements
curans += pq.get(0);
pq.remove(0);
// Update the answer
ans = Math.max(ans, curans);
}
}
}
// Return the maximized sub-array sum
return ans;
}
// Driver code.
public static void main (String[] args)
{
int[] a = { 5, -1, 2, 3, 4, -2, 5 };
int x = 2;
int n = a.length;
System.out.println(SubarraySum(a, n, x));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 implementation of the approach
# Function to return the maximum
# sub-array sum after at most x swaps
def SubarraySum(a, n, x) :
# To store the required answer
ans = -10000
# For all possible intervals
for i in range(n) :
for j in range(i, n) :
# Keep current ans as zero
curans = 0
# To store the integers which are
# not part of the sub-array
# currently under consideration
pq = []
# To store elements which are
# part of the sub-array
# currently under consideration
pq2 = []
# Create two sets
for k in range(n) :
if (k >= i and k <= j) :
curans += a[k]
pq2.append(a[k])
else :
pq.append(a[k])
pq.sort()
pq.reverse()
pq2.sort()
ans = max(ans, curans)
# Swap at most X elements
for k in range(1, x + 1) :
if (len(pq) == 0 or len(pq2) == 0 or pq2[0] >= pq[0]) :
break
# Remove the minimum of
# the taken elements
curans -= pq2[0]
pq2.pop(0)
# Add maximum of the
# discarded elements
curans += pq[0]
pq.pop(0)
# Update the answer
ans = max(ans, curans)
# Return the maximized sub-array sum
return ans
# Driver code
a = [ 5, -1, 2, 3, 4, -2, 5 ]
x = 2;
n = len(a)
print(SubarraySum(a, n, x))
# This code is contributed by divyesh072019.
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to return the maximum
// sub-array sum after at most x swaps
static int SubarraySum(int[] a, int n, int x)
{
// To store the required answer
int ans = -10000;
// For all possible intervals
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
// Keep current ans as zero
int curans = 0;
// To store the integers which are
// not part of the sub-array
// currently under consideration
List<int> pq = new List<int>();
// To store elements which are
// part of the sub-array
// currently under consideration
List<int> pq2 = new List<int>();
// Create two sets
for (int k = 0; k < n; k++) {
if (k >= i && k <= j) {
curans += a[k];
pq2.Add(a[k]);
}
else
pq.Add(a[k]);
}
pq.Sort();
pq.Reverse();
pq2.Sort();
ans = Math.Max(ans, curans);
// Swap at most X elements
for (int k = 1; k <= x; k++) {
if (pq.Count == 0 || pq2.Count == 0
|| pq2[0] >= pq[0])
break;
// Remove the minimum of
// the taken elements
curans -= pq2[0];
pq2.RemoveAt(0);
// Add maximum of the
// discarded elements
curans += pq[0];
pq.RemoveAt(0);
// Update the answer
ans = Math.Max(ans, curans);
}
}
}
// Return the maximized sub-array sum
return ans;
}
// Driver code.
static void Main() {
int[] a = { 5, -1, 2, 3, 4, -2, 5 };
int x = 2;
int n = a.Length;
Console.WriteLine(SubarraySum(a, n, x));
}
}
// This code is contributed by divyeshrabaiya07.
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the maximum
// sub-array sum after at most x swaps
function SubarraySum(a, n, x)
{
// To store the required answer
let ans = -10000;
// For all possible intervals
for (let i = 0; i < n; i++)
{
for (let j = i; j < n; j++)
{
// Keep current ans as zero
let curans = 0;
// To store the integers which are
// not part of the sub-array
// currently under consideration
let pq = [];
// To store elements which are
// part of the sub-array
// currently under consideration
let pq2 = [];
// Create two sets
for (let k = 0; k < n; k++) {
if (k >= i && k <= j) {
curans += a[k];
pq2.push(a[k]);
}
else
pq.push(a[k]);
}
pq.sort();
pq.reverse();
pq2.sort();
ans = Math.max(ans, curans);
// Swap at most X elements
for (let k = 1; k <= x; k++) {
if (pq.length == 0 || pq2.length == 0
|| pq2[0] >= pq[0])
break;
// Remove the minimum of
// the taken elements
curans -= pq2[0];
pq2.shift();
// Add maximum of the
// discarded elements
curans += pq[0];
pq.shift();
// Update the answer
ans = Math.max(ans, curans);
}
}
}
// Return the maximized sub-array sum
return ans;
}
let a = [ 5, -1, 2, 3, 4, -2, 5 ];
let x = 2;
let n = a.length;
document.write(SubarraySum(a, n, x));
// This code is contributed by suresh07.
</script>
Time Complexity: O(n3 logn)
Auxiliary Space: O(n)
Similar Reads
Maximum subarray sum possible after removing at most K array elements Given an array arr[] of size N and an integer K, the task is to find the maximum subarray sum by removing at most K elements from the array. Examples: Input: arr[] = { -2, 1, 3, -2, 4, -7, 20 }, K = 1 Output: 26 Explanation: Removing arr[5] from the array modifies arr[] to { -2, 1, 3, -2, 4, 20 } Su
15+ min read
Maximum possible sum after M operations on N cards Given an array arr[] of size N which represents the initial number on each card and given a two dimensional array B[][] of size M where M represents the number of operations that need to be performed. At each operation, choose at most B[j][0] cards (possibly zero) and replace the integer written on
8 min read
Maximum possible Array sum after performing given operations Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer
9 min read
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
7 min read
Maximum Subarray Sum after inverting at most two elements Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
11 min read
Maximum sum subarray after altering the array Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4,
15+ min read
Maximize Array sum by swapping at most K elements with another array Given two arrays A and B of size N and an integer K, the task is to find the maximum possible sum of array A by swapping at most K elements with array B. Examples: Input: A[] = {2, 3, 4}, B[] = {6, 8, 5}, K = 1 Output: 15 Explanation: Swap A[0] and B[1]. Hence sum = 8 + 3 + 4 = 15. Input: A[] = {9,
6 min read
Length of the smallest subarray with maximum possible sum Given an array arr[] consisting of N non-negative integers, the task is to find the minimum length of the subarray whose sum is maximum. Example: Input: arr[] = {0, 2, 0, 0, 12, 0, 0, 0}Output: 4Explanation: The sum of the subarray {2, 0, 0, 12} = 2 + 0 + 0 + 12 = 14, which is maximum sum possible a
6 min read
Collect maximum points in an array with k moves Given an array of integer and two values k and i where k is the number of moves and i is the index in the array. The task is to collect maximum points in the array by moving either in single or both directions from given index i and making k moves. Note that every array element visited is considered
9 min read
Minimum possible sum of array elements after performing the given operation Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
9 min read