Maximums from array when the maximum decrements after every access in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[]and an integer M. Our task is to create a program to find Maximums from array when the maximum decrements after every access in C++.

Problem Description

To find the maximum, we will find the maximum element from the array and after every retrieval and decrease it by -1, M times.

Let’s take an example to understand the problem,

Input: arr[] = {3, 6, 8, 9} M = 2

Ouput:17

Explanation

1st iteration, maximum = 9, sum = 9, updated arr = {3, 6, 8, 8}

2nd iteration, maximum = 8, sum = 9+8 = 17, updated arr = {3, 6, 7, 8}

Solution Approach

A simple solution is to use the max heap which will have the max element at root. Then pop the root, decrease it by 1, then insert the element again. This is pop and insert is done M times. For each pop operation, we will add the element to the sum element and print the sum after M iterations.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getSum(int arr[], int N, int M) {
   int sumVal = 0;
   priority_queue<int> heap;
   for (int i = 0; i < N; i++)
      heap.push(arr[i]);
   while (M--) {
      int maximumVal = heap.top();
      sumVal += maximumVal;
      heap.pop();
      heap.push(maximumVal - 1);
   }
   return sumVal;
}
int main() {
   int arr[] = { 3, 6, 8, 9};
   int M = 2;
   int N = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum from array when the maximum decrements after every access is "<<getSum(arr, N,M);
}

Output

The maximum from array when the maximum decrements after every access is 17
raja
Updated on 09-Oct-2020 09:33:33

Advertisements