Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmMaximize array sum by replacing at most L elements to R for...

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[]= {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 queries
void 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 Code
int 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 approach
from queue import PriorityQueue
 
# Function to find the maximum array
# sum after performing M queries
def 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 Code
N = 3
M = 2
arr = [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 approach
using 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 Code
let N = 3, M = 2;
let arr = [5, 1, 4];
let Query = [[2, 3], [1, 5]];
 
maximumArraySumWithMQuery(arr, Query, N, M);


Output: 

14

 

Time Complexity: O(M*N*log N)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments