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[]= {5, 1, 4}, Query[][] = {{2, 3}, {1, 5}}
Output: 14
Explanation:
Following are the operations performed:
Query 1: For the Query {2, 3}, do nothing.
Query 2: For the Query {1, 5}, replace at most L(= 1) array element with value R(= 5), replace arr[1] with value 5.
After the above steps, array modifies to {5, 5, 4}. The sum of array element is 14, which is maximum.Input: arr[] = {1, 2, 3, 4}, Query[][] = {{3, 1}, {2, 5}}
Output: 17
Approach: The given problem can be solved with the help of the Greedy Approach. The main idea to maximize the array sum is to perform the query to increase the minimum number to a maximum value as the order of the operations does not matter as they are independent of each other. Follow the steps below to solve the given problem:
- Maintain a min-heap priority queue and store all the array elements.
- Traverse the given array of queries Q[][] and for each query {L, R} perform the following steps:
- Change the value of at most L elements smaller than R to the value R, starting from the smallest.
- Perform the above operation, pop the elements smaller than R and push R at their places in the priority queue.
- After completing the above steps, print the sum of values stored in the priority queue as the maximum sum.
Below is the implementation of the above approach:Â
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the maximum array// sum after performing M queriesvoid maximumArraySumWithMQuery(    int arr[], vector<vector<int> >& Q,    int N, int M){Â
    // Maintain a min-heap Priority-Queue    priority_queue<int, vector<int>,                   greater<int> >        pq;Â
    // Push all the elements in the    // priority queue    for (int i = 0; i < N; i++) {        pq.push(arr[i]);    }Â
    // Iterate through M Operations    for (int i = 0; i < M; i++) {Â
        // Iterate through the total        // possible changes allowed        // and maximize the array sum        int l = Q[i][0];        int r = Q[i][1];Â
        for (int j = 0; j < l; j++) {Â
            // Change the value of elements            // less than r to r, starting            // from the smallest            if (pq.top() < r) {                pq.pop();                pq.push(r);            }Â
            // Break if current element >= R            else {                break;            }        }    }Â
    // Find the resultant maximum sum    int ans = 0;Â
    while (!pq.empty()) {        ans += pq.top();        pq.pop();    }Â
    // Print the sum    cout << ans;}Â
// Driver Codeint main(){    int N = 3, M = 2;    int arr[] = { 5, 1, 4 };    vector<vector<int> > Query        = { { 2, 3 }, { 1, 5 } };Â
    maximumArraySumWithMQuery(        arr, Query, N, M);Â
    return 0;} |
Java
// Java program for the above approachÂ
import java.util.PriorityQueue;Â
class GFG {Â
    // Function to find the maximum array    // sum after performing M queries    public static void maximumArraySumWithMQuery(int arr[], int[][] Q, int N, int M) {Â
        // Maintain a min-heap Priority-Queue        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();Â
        // Push all the elements in the        // priority queue        for (int i = 0; i < N; i++) {            pq.add(arr[i]);        }Â
        // Iterate through M Operations        for (int i = 0; i < M; i++) {Â
            // Iterate through the total            // possible changes allowed            // and maximize the array sum            int l = Q[i][0];            int r = Q[i][1];Â
            for (int j = 0; j < l; j++) {Â
                // Change the value of elements                // less than r to r, starting                // from the smallest                if (pq.peek() < r) {                    pq.remove();                    pq.add(r);                }Â
                // Break if current element >= R                else {                    break;                }            }        }Â
        // Find the resultant maximum sum        int ans = 0;Â
        while (!pq.isEmpty()) {            ans += pq.peek();            pq.remove();        }Â
        // Print the sum        System.out.println(ans);    }Â
    // Driver Code    public static void main(String args[]) {        int N = 3, M = 2;        int arr[] = { 5, 1, 4 };        int[][] Query = { { 2, 3 }, { 1, 5 } };Â
        maximumArraySumWithMQuery(arr, Query, N, M);Â
    }}Â
// This code is contributed by saurabh_jaiswal. |
Python3
# Python program for the above approachfrom queue import PriorityQueueÂ
# Function to find the maximum array# sum after performing M queriesdef maximumArraySumWithMQuery(arr, Q, N, M):Â
    # Maintain a min-heap Priority-Queue    pq = PriorityQueue()Â
    # Push all the elements in the    # priority queue    for i in range(N):        pq.put(arr[i])Â
    # Iterate through M Operations    for i in range(M):Â
        # Iterate through the total        # possible changes allowed        # and maximize the array sum        l = Q[i][0];        r = Q[i][1];Â
        for j in range(l):Â
            # Change the value of elements            # less than r to r, starting            # from the smallest            if (pq.queue[0] < r):                pq.get();                pq.put(r); Â
            # Break if current element >= R            else:                break             # Find the resultant maximum sum    ans = 0;         while ( not pq.empty() ):        ans += pq.queue[0];        pq.get(); Â
    # Print the sum    print(ans) Â
# Driver CodeN = 3M = 2arr = [5, 1, 4]Query = [[2, 3], [1, 5]]Â
maximumArraySumWithMQuery(arr, Query, N, M)Â
# This code is contributed by gfgking. |
C#
// C# Program for the above approachusing System;using System.Collections.Generic;Â
public class GFG {Â
  // Function to find the maximum array  // sum after performing M queries  public static void maximumArraySumWithMQuery(int[] arr,                                               int[, ] Q,                                               int N,                                               int M)  {Â
    // Maintain a min-heap Priority-Queue    List<int> pq = new List<int>();Â
    // Push all the elements in the    // priority queue    for (int i = 0; i < N; i++) {      pq.Add(arr[i]);    }    pq.Sort();Â
    // Iterate through M Operations    for (int i = 0; i < M; i++) {Â
      // Iterate through the total      // possible changes allowed      // and maximize the array sum      int l = Q[i, 0];      int r = Q[i, 1];Â
      for (int j = 0; j < l; j++) {Â
        // Change the value of elements        // less than r to r, starting        // from the smallest        if (pq[0] < r) {          pq.Remove(pq[0]);          pq.Add(r);          pq.Sort();        }Â
        // Break if current element >= R        else {          break;        }      }    }Â
    // Find the resultant maximum sum    int ans = 0;Â
    while (pq.Count > 0) {      ans += pq[0];      pq.Remove(pq[0]);    }Â
    // Print the sum    Console.WriteLine(ans);  }Â
  // Driver Code  public static void Main(string[] args)  {    int N = 3, M = 2;    int[] arr = { 5, 1, 4 };    int[, ] Query = { { 2, 3 }, { 1, 5 } };Â
    maximumArraySumWithMQuery(arr, Query, N, M);  }}Â
// This code is contributed by akashish__ |
Javascript
function maximumArraySumWithMQuery(arr, Q, N, M) {Â Â Â Â let pq = [];Â
    // Push all the elements in the    // priority queue    for (let i = 0; i < N; i++) {        pq.push(arr[i]);    }Â
    // Iterate through M Operations    for (let i = 0; i < M; i++) {Â
        // Iterate through the total        // possible changes allowed        // and maximize the array sum        let l = Q[i][0];        let r = Q[i][1];Â
        for (let j = 0; j < l; j++) {Â
            // Change the value of elements            // less than r to r, starting            // from the smallest            if (pq[0] < r) {                pq.shift();                pq.push(r);                pq.sort((a, b) => a - b);            }Â
            // Break if current element >= R            else {                break;            }        }    }Â
    // Find the resultant maximum sum    let ans = 1;Â
    while (pq.length > 0) {        ans += pq.shift() + 1;    }Â
    // Print the sum    console.log(ans);}Â
// Driver Codelet N = 3, M = 2;let arr = [5, 1, 4];let Query = [[2, 3], [1, 5]];Â
maximumArraySumWithMQuery(arr, Query, N, M); |
14
Â
Time Complexity: O(M*N*log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
