Perform K of Q queries to maximize the sum of the array elements

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)

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 contriution 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 contriution of every query 
    for (int i = 0; i < q; i++)
    
        contribution.add(queries[i].second 
                            - queries[i].first + 1); 
    
      
    //compartor 
    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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 contriution 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

chevron_right


Output:

23


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.