Maximum sum after rearranging the array for K queries
Last Updated :
04 Jan, 2023
Given two arrays arr[] containing N integers and Q[][] containing K queries where every query represents a range [L, R]. The task is to rearrange the array and find the maximum possible sum of all the subarrays where each subarray is defined by the elements of the array in the range [L, R] given by each query.
Note: 1-based indexing is used in the Q[][] array to signify the ranges.
Examples:
Input: arr[] = { 2, 6, 10, 1, 5, 6 }, Q[][2] = {{1, 3}, {4, 6}, {3, 4}}
Output: 46
Explanation:
One possible way is to rearrange the array to arr[] = {2, 6, 10, 6, 5, 1}.
In this arrangement:
The sum of the subarray in the range [1, 3] = 2 + 6 + 10 = 18.
The sum of the subarray in the range [4, 6] = 6 + 5 + 1 = 12.
The sum of the subarray in the range [3, 4] = 10 + 6 = 16.
The total sum of all the subarrays = 46 which is the maximum possible.
Input: arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }, Q[][2] = {{1, 4}, {5, 5}, {7, 8}, {8, 8}}
Output: 43
Explanation:
One possible way is to rearrange the array to arr[] = {2, 3, 4, 5, 6, 1, 7, 8}.
In this arrangement:
The sum of the subarray in the range [1, 4] = 2 + 3 + 4 + 5 = 14.
The sum of the subarray in the range [5, 5] = 6 = 6.
The sum of the subarray in the range [7, 8] = 7 + 8 = 15.
The sum of the subarray in the range [8, 8] = 8 = 8.
The total sum of all the subarrays = 43 which is the maximum possible.
Approach: On observing clearly, one conclusion which can be made is that we get the maximum sum when the maximum elements are included in as many subarrays as possible. For this, we need to find the number of times every index is included by iterating all the queries.
For example: Let the array be arr[] = {2, 6, 10, 6, 5, 1} and the queries be Q[][] = {{1, 3}, {4, 6}, {3, 4}}.
- Step 1: Create a count array C[] of size N. So, initially, the count array C[] = {0, 0, 0, 0, 0, 0}.
- Step 2: For the query [1, 3], the elements at the index [1, 3] are incremented by 1. The count array after this query becomes {1, 1, 1, 0, 0, 0}.
- Step 3: Similarly, for the next query, the count array becomes {1, 1, 1, 1, 1, 1} and finally, after the third query, the count array becomes {1, 1, 2, 2, 1, 1}.
- Step 4: After obtaining the count array, the idea is to use sorting to get the maximum sum.
- Step 5: After sorting, the array C[] = {1, 1, 1, 1, 2, 2} and arr[] = {1, 2, 5, 6, 6, 10}. The maximum possible sum is the weighted sum of both the arrays, i.e.:
sum = ((1 * 1) + (1 * 2) + (1 * 5) + (1 * 6) + (2 * 6) + (2 * 10)) = 46
Below is the implementation of the above approach:
C++
// C++ program to find the maximum sum
// after rearranging the array for K queries
#include <bits/stdc++.h>
using namespace std;
// Function to find maximum sum after
// rearranging array elements
int maxSumArrangement(int A[], int R[][2],
int N, int M)
{
// Auxiliary array to find the
// count of each selected elements
int count[N];
// Initialize with 0
memset(count, 0, sizeof count);
// Finding count of every element
// to be selected
for (int i = 0; i < M; ++i) {
int l = R[i][0], r = R[i][1] + 1;
// Making it to 0-indexing
l--;
r--;
// Prefix sum array concept is used
// to obtain the count array
count[l]++;
if (r < N)
count[r]--;
}
// Iterating over the count array
// to get the final array
for (int i = 1; i < N; ++i) {
count[i] += count[i - 1];
}
// Variable to store the maximum sum
int ans = 0;
// Sorting both the arrays
sort(count, count + N);
sort(A, A + N);
// Loop to find the maximum sum
for (int i = N - 1; i >= 0; --i) {
ans += A[i] * count[i];
}
return ans;
}
// Driver code
int main()
{
int A[] = { 2, 6, 10, 1, 5, 6 };
int R[][2]
= { { 1, 3 }, { 4, 6 }, { 3, 4 } };
int N = sizeof(A) / sizeof(A[0]);
int M = sizeof(R) / sizeof(R[0]);
cout << maxSumArrangement(A, R, N, M);
return 0;
}
Java
// Java program to find the maximum sum
// after rearranging the array for K queries
import java.util.*;
class GFG
{
// Function to find maximum sum after
// rearranging array elements
static int maxSumArrangement(int A[], int R[][],
int N, int M)
{
// Auxiliary array to find the
// count of each selected elements
int count[] = new int[N];
int i;
// Finding count of every element
// to be selected
for ( i = 0; i < M; ++i) {
int l = R[i][0], r = R[i][1] + 1;
// Making it to 0-indexing
l--;
r--;
// Prefix sum array concept is used
// to obtain the count array
count[l]++;
if (r < N)
count[r]--;
}
// Iterating over the count array
// to get the final array
for (i = 1; i < N; ++i) {
count[i] += count[i - 1];
}
// Variable to store the maximum sum
int ans = 0;
// Sorting both the arrays
Arrays.sort( count);
Arrays.sort(A);
// Loop to find the maximum sum
for (i = N - 1; i >= 0; --i) {
ans += A[i] * count[i];
}
return ans;
}
// Driver code
public static void main(String []args)
{
int A[] = { 2, 6, 10, 1, 5, 6 };
int R[][]
= { { 1, 3 }, { 4, 6 }, { 3, 4 } };
int N = A.length;
int M = R.length;
System.out.print(maxSumArrangement(A, R, N, M));
}
}
// This code is contributed by chitranayal
Python3
# Python3 program to find the maximum sum
# after rearranging the array for K queries
# Function to find maximum sum after
# rearranging array elements
def maxSumArrangement( A, R, N, M):
# Auxiliary array to find the
# count of each selected elements
# Initialize with 0
count = [0 for i in range(N)]
# Finding count of every element
# to be selected
for i in range(M):
l = R[i][0]
r = R[i][1] + 1
# Making it to 0-indexing
l = l - 1
r = r - 1
# Prefix sum array concept is used
# to obtain the count array
count[l] = count[l] + 1
if (r < N):
count[r] = count[r] - 1
# Iterating over the count array
# to get the final array
for i in range(1, N):
count[i] = count[i] + count[i - 1]
# Variable to store the maximum sum
ans = 0
# Sorting both the arrays
count.sort()
A.sort()
# Loop to find the maximum sum
for i in range(N - 1, -1, -1):
ans = ans + A[i] * count[i]
return ans
# Driver code
A = [ 2, 6, 10, 1, 5, 6 ]
R = [ [ 1, 3 ], [ 4, 6 ], [ 3, 4 ] ]
N = len(A)
M = len(R)
print(maxSumArrangement(A, R, N, M))
# This code is contributed by Sanjit_Prasad
C#
// C# program to find the maximum sum
// after rearranging the array for K queries
using System;
class GFG
{
// Function to find maximum sum after
// rearranging array elements
static int maxSumArrangement(int []A, int [,]R,
int N, int M)
{
// Auxiliary array to find the
// count of each selected elements
int []count = new int[N];
int i;
// Finding count of every element
// to be selected
for ( i = 0; i < M; ++i) {
int l = R[i, 0], r = R[i, 1] + 1;
// Making it to 0-indexing
l--;
r--;
// Prefix sum array concept is used
// to obtain the count array
count[l]++;
if (r < N)
count[r]--;
}
// Iterating over the count array
// to get the readonly array
for (i = 1; i < N; ++i) {
count[i] += count[i - 1];
}
// Variable to store the maximum sum
int ans = 0;
// Sorting both the arrays
Array.Sort( count);
Array.Sort(A);
// Loop to find the maximum sum
for (i = N - 1; i >= 0; --i) {
ans += A[i] * count[i];
}
return ans;
}
// Driver code
public static void Main(String []args)
{
int []A = { 2, 6, 10, 1, 5, 6 };
int [,]R
= { { 1, 3 }, { 4, 6 }, { 3, 4 } };
int N = A.Length;
int M = R.GetLength(0);
Console.Write(maxSumArrangement(A, R, N, M));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
//Javascript program to find the maximum sum
// after rearranging the array for K queries
//function to sort a array
function arrSort(a, n) {
var i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
// Function to find maximum sum after
// rearranging array elements
function maxSumArrangement(A, R, N, M)
{
// Auxiliary array to find the
// count of each selected elements
var count = new Array(N);
// Initialize with 0
count.fill(0);
// Finding count of every element
// to be selected
for (var i = 0; i < M; i++) {
var l = R[i][0], r = R[i][1] + 1;
// Making it to 0-indexing
l--;
r--;
// Prefix sum array concept is used
// to obtain the count array
count[l]++;
if (r < N)
count[r]--;
}
// Iterating over the count array
// to get the final array
for (var i = 1; i < N; ++i) {
count[i] += count[i - 1];
}
// Variable to store the maximum sum
var ans = 0;
// Sorting both the arrays
count.sort();
arrSort(A,N);
// Loop to find the maximum sum
for (var i = N - 1; i >= 0; --i) {
ans += A[i] * count[i];
}
return ans;
}
var A = [ 2, 6, 10, 1, 5, 6 ];
var R = [ [ 1, 3 ], [ 4, 6 ], [ 3, 4 ] ];
var N = A.length;
var M = R.length;
document.write( maxSumArrangement(A, R, N, M));
//This code is contributed by SoumikMondal
</script>
Time Complexity: O(N* log(N))
Auxiliary Space: O(N), where N is the size of the given array.
Similar Reads
Maximum sum of segments among all segments formed in array after Q queries Given two arrays arr[](1-based indexing) and queries[] consisting of N integers and queries[] contains a permutation of the first N natural numbers, the task is to perform the query on the array and find the maximum sum of segments among all segments formed such that in each query queries[i] the arr
15 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
Queries to find the maximum array element after removing elements from a given range Given an array arr[] and an array Q[][] consisting of queries of the form of {L, R}, the task for each query is to find the maximum array element after removing array elements from the range of indices [L, R]. If the array becomes empty after removing the elements from given range of indices, then p
10 min read
Maximize array sum by replacing at most L elements to R for Q queries Given an array arr[] consisting of N integers and an array Query[][] consisting of M pairs of the type {L, R}, the task is to find the maximum sum of the array by performing the queries Query[][] such that for each query {L, R} replace at most L array elements to the value R. Examples: Input: arr[]=
7 min read
Sum of Array maximums after K operations by reducing max element to its half Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the array is replaced with its half. Example: Input: arr[] = {2, 4, 6, 8, 10}, K = 5Output: 33Explanation: In 1st operation, the maximum of
6 min read