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 sumint 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 codeint 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 classstatic 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 sumdef 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 codeif __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> |
23
Â
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
