Perform K of Q queries to maximize the sum of the array elements
Last Updated :
28 Feb, 2023
Given an array arr[] of N integers and an integer K. Also given are Q queries which have two numbers L and R. For every query, you can increase all the elements of the array in the index range [L, R] by 1. The task is to choose exactly K queries out of Q queries such that the sum of the array at the end is maximized. Print the sum after performing K such queries.
Examples:
Input: arr[] = {1, 1, 2, 2, 2, 3},
que[] = {{0, 4}, {1, 2}, {2, 5}, {2, 3}, {2, 4}},
K = 3
Output: 23
We choose the first, third and the fifth query.
After performing first query -> arr[] = {2, 2, 3, 3, 3, 3}
After performing third query -> arr[] = {2, 2, 4, 4, 4, 4}
After performing fifth query -> arr[] = {2, 2, 5, 5, 5, 4}
And the array sum is 2 + 2 + 5 + 5 + 5 + 4 = 23.
Input: arr[] = {4, 5, 4, 21, 22},
que[] = {{1, 2}, {2, 2}, {2, 4}, {2, 2}},
K = 2
Output: 61
Naive approach: A naive approach is to use Dynamic Programming and Combinatorics, in which we choose any K queries out of Q. The combination which gives the maximum sum of the array will be the answer.
Time Complexity: O(N*N*K), as we will use recursion with memorization.
Auxiliary Space: O(N*N*K), as we will be using extra space for the memorization.
Efficient Approach: Since we need to maximize the sum of the array at the end. We just need to choose those queries that affect the maximum number of elements from the array i.e. with bigger ranges. Every query contributes (R - L + 1) to the increase in the sum if it is chosen. The sum of the array elements after performing such queries will be (initial sum of the array + (Contribution of K queries)).
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to perform K queries out
// of Q to maximize the final sum
int getFinalSum(int a[], int n, pair<int, int> queries[],
int q, int k)
{
int answer = 0;
// Get the initial sum
// of the array
for (int i = 0; i < n; i++)
answer += a[i];
vector<int> contribution;
// Stores the contribution of every query
for (int i = 0; i < q; i++) {
contribution.push_back(queries[i].second
- queries[i].first + 1);
}
// Sort the contribution of queries
// in descending order
sort(contribution.begin(), contribution.end(),
greater<int>());
int i = 0;
// Get the K most contributions
while (i < k) {
answer += contribution[i];
i++;
}
return answer;
}
// Driver code
int main()
{
int a[] = { 1, 1, 2, 2, 2, 3 };
int n = sizeof(a) / sizeof(a[0]);
pair<int, int> queries[] = { { 0, 4 },
{ 1, 2 },
{ 2, 5 },
{ 2, 3 },
{ 2, 4 } };
int q = sizeof(queries) / sizeof(queries[0]);
int k = 3;
cout << getFinalSum(a, n, queries, q, k);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
//pair class
static class pair
{
int first,second;
pair(int f,int s)
{
first = f;
second = s;
}
}
// Function to perform K queries out
// of Q to maximize the final sum
static int getFinalSum(int a[], int n, pair queries[],
int q, int k)
{
int answer = 0;
// Get the initial sum
// of the array
for (int i = 0; i < n; i++)
answer += a[i];
Vector<Integer> contribution = new Vector<Integer>();
// Stores the contribution of every query
for (int i = 0; i < q; i++)
{
contribution.add(queries[i].second
- queries[i].first + 1);
}
//comparator
Comparator<Integer> Comp = new Comparator<Integer>()
{
public int compare(Integer e1,Integer e2)
{
if(e1 > e2)
return -1;
else
return 1;
}
};
// Sort the contribution of queries
// in descending order
Collections.sort(contribution,Comp);
int i = 0;
// Get the K most contributions
while (i < k)
{
answer += (int) contribution.get(i);
i++;
}
return answer;
}
// Driver code
public static void main(String args[])
{
int a[] = { 1, 1, 2, 2, 2, 3 };
int n = a.length;
pair queries[] = new pair[5];
queries[0] = new pair( 0, 4 );
queries[1] = new pair( 1, 2 );
queries[2] = new pair( 2, 5 );
queries[3] = new pair( 2, 3 );
queries[4] = new pair( 2, 4 );
int q = queries.length;
int k = 3;
System.out.println( getFinalSum(a, n, queries, q, k));
}
}
// This code is contributed by Arnab Kundu
Python3
# Python 3 implementation of the approach
# Function to perform K queries out
# of Q to maximize the final sum
def getFinalSum(a, n, queries, q, k):
answer = 0
# Get the initial sum
# of the array
for i in range(n):
answer += a[i]
contribution = []
# Stores the contribution of every query
for i in range(q):
contribution.append(queries[i][1]-
queries[i][0] + 1)
# Sort the contribution of queries
# in descending order
contribution.sort(reverse = True)
i = 0
# Get the K most contributions
while (i < k):
answer += contribution[i]
i += 1
return answer
# Driver code
if __name__ == '__main__':
a = [1, 1, 2, 2, 2, 3]
n = len(a)
queries = [[0, 4], [1, 2],
[2, 5], [2, 3],
[2, 4]]
q = len(queries);
k = 3
print(getFinalSum(a, n, queries, q, k))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG
{
// pair class
public class pair
{
public int first, second;
public pair(int f, int s)
{
first = f;
second = s;
}
}
// Function to perform K queries out
// of Q to maximize the final sum
public static int getFinalSum(int[] a, int n, pair[] queries, int q, int k)
{
int answer = 0;
// Get the initial sum
// of the array
for (int i = 0; i < n; i++)
answer += a[i];
List<int> contribution = new List<int>();
// Stores the contribution of every query
for (int i = 0; i < q; i++)
{
contribution.Add(queries[i].second
- queries[i].first + 1);
}
// Sort the contribution of queries
// in descending order
contribution.Sort();
contribution.Reverse();
int j = 0;
// Get the K most contributions
while (j < k)
{
answer += contribution[j];
j++;
}
return answer;
}
// Driver code
public static void Main(String[] args)
{
int[] a = { 1, 1, 2, 2, 2, 3 };
int n = a.Length;
pair[] queries = new pair[5];
queries[0] = new pair(0, 4);
queries[1] = new pair(1, 2);
queries[2] = new pair(2, 5);
queries[3] = new pair(2, 3);
queries[4] = new pair(2, 4);
int q = queries.Length;
int k = 3;
Console.WriteLine(getFinalSum(a, n, queries, q, k));
}
}
JavaScript
<script>
// JavaScript implementation of the approach
// Function to perform K queries out
// of Q to maximize the final sum
const getFinalSum = (a, n, queries, q, k) => {
let answer = 0;
// Get the initial sum
// of the array
for (let i = 0; i < n; i++)
answer += a[i];
let contribution = [];
// Stores the contribution of every query
for (let i = 0; i < q; i++) {
contribution.push(queries[i][1] - queries[i][0] + 1);
}
// Sort the contribution of queries
// in descending order
contribution.sort((a, b) => b - a);
let i = 0;
// Get the K most contributions
while (i < k) {
answer += contribution[i];
i++;
}
return answer;
}
// Driver code
const a = [1, 1, 2, 2, 2, 3];
const n = a.length;
const queries = [
[0, 4],
[1, 2],
[2, 5],
[2, 3],
[2, 4]
];
const q = queries.length;
let k = 3;
document.write(getFinalSum(a, n, queries, q, k));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(max(n,k,q*log(q))), as we are using a loop to traverse n and k times and we are using a sort function to sort an array of size q.
Auxiliary Space: O(q), as we are using extra space for the array contribution.
Similar Reads
Maximize the sum of sum of the Array by removing end elements
Given an array arr of size N, the task is to maximize the sum of sum, of the remaining elements in the array, by removing the end elements.Example: Input: arr[] = {2, 3} Output: 3 Explanation: At first we will delete 2, then sum of remaining elements = 3. Then delete 3. Therefore sum of sum = 3 + 0
6 min read
Remove array end element to maximize the sum of product
Given an array of N positive integers. We are allowed to remove element from either of the two ends i.e from the left side or right side of the array. Each time we remove an element, score is increased by value of element * (number of element already removed + 1). The task is to find the maximum sco
9 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximize the Sum of the given array using given operations
Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to maximize the sum calculated from the array A[] by the following operations: For every index in B[] containing 0, the corresponding index in A[] is added to the sum.For every index in B[] containing 1, add the valu
7 min read
Maximize count of array elements required to obtain given sum
Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1. Examples: Input: arr[] =
8 min read
Maximum element present in the array after performing queries to add K to range of indices [L, R]
Given an array arr[] consisting of N integers, ( initially set to 0 ) and an array Q[], consisting of queries of the form {l, r, k}, the task for each query is to add K to the indices l to r(both inclusive). After performing all queries, return the maximum element present the array. Example: Input:
7 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
Find sum of all unique elements in the array for K queries
Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based index
8 min read
Sum of all array elements less than X and greater than Y for Q queries
Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array. Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12},
9 min read
Find the Maximum sum of the Array by performing the given operations
Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
5 min read