Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Heap
  • Practice Heap
  • MCQs on Heap
  • Heap Tutorial
  • Binary Heap
  • Building Heap
  • Binomial Heap
  • Fibonacci Heap
  • Heap Sort
  • Heap vs Tree
  • Leftist Heap
  • K-ary Heap
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize operations to reduce Array sum by half by reducing any elements by half
Next article icon

Maximize array sum by replacing at most L elements to R for Q queries

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)


Next Article
Minimize operations to reduce Array sum by half by reducing any elements by half

K

kartikmodi
Improve
Article Tags :
  • Greedy
  • Sorting
  • Heap
  • DSA
  • Arrays
  • array-range-queries
  • min-heap
Practice Tags :
  • Arrays
  • Greedy
  • Heap
  • Sorting

Similar Reads

  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Minimize cost for reducing array by replacing two elements with sum at most K times for any index
    Given an array arr[] of size N and an integer K. The task is to find the minimum cost required to collect the sum of the array. The sum of the array is collected by picking any element and adding it to an element of any index in the array. The addition of elements at the same index is allowed for at
    11 min read
  • Most frequent element in Array after replacing given index by K for Q queries
    Given an array arr[] of size N, and Q queries of the form {i, k} for which, the task is to print the most frequent element in the array after replacing arr[i] by k.Example : Input: arr[] = {2, 2, 2, 3, 3}, Query = {{0, 3}, {4, 2}, {0, 4}} Output: 3 2 2 First query: Setting arr[0] = 3 modifies arr[]
    10 min read
  • Minimize Array sum by replacing L and R elements from both end with X and Y
    Given an array A[] of N integers and 2 integers X and Y. The task is to minimize the sum of all elements of the array by choosing L and R and replacing the initial L elements with X and the R elements from the end with Y. Examples: Input: N = 5, X = 4, Y = 3, A[] = {5, 5, 0, 6, 3}Output: 14Explanati
    8 min read
  • Minimize operations to reduce Array sum by half by reducing any elements by half
    Given an array Arr[], the task is to find out the minimum number of operations to make the sum of array elements lesser or equal to half of its initial value. In one such operation, it is allowed to half the value of any array element. Examples: Input: Arr[] = [4, 6, 3, 9, 10, 2]Output: 5Explanation
    5 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
  • 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
    7 min read
  • Maximize subarray sum of given Array by adding X in range [L, R] for Q queries
    Given an array arr[] of N integers and M update queries of the type (L, R, X), the task is to find the maximum subarray sum after each update query where in each query, add integer X to every element of the array arr[] in the range [L, R]. Examples: Input: arr[] = {-1, 5, -2, 9, 3, -3, 2}, query[] =
    8 min read
  • Sum of Array maximums after K operations by reducing max element to its half
    Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the array is replaced with its half. Example: Input: arr[] = {2, 4, 6, 8, 10}, K = 5Output: 33Explanation: In 1st operation, the maximum of
    6 min read
  • Queries for number of array elements in a range with Kth Bit Set
    Given an array of N positive (32-bit)integers, the task is to answer Q queries of the following form: Query(L, R, K): Print the number of elements of the array in the range L to R, which have their Kth bit as set Note: Consider LSB to be indexed at 1. Examples: Input : arr[] = { 8, 9, 1, 3 } Query 1
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences