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

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximums from array when the maximum decrements after every access.

For this we will be provided with an array containing integers and a value K. Our task is to find the maximum value of array, add it to sum and decrement it by 1 performing this operation K times.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll getSum(int arr[], int K, int n) {
   ll sum = 0;
   priority_queue<ll> maxHeap;
   for (ll i = 0; i < n; i++) {
      //placing elements in a heap
      maxHeap.push(arr[i]);
   }
   while (K--) {
      ll currentMax = maxHeap.top();
      sum += currentMax;
      maxHeap.pop();
      maxHeap.push(currentMax - 1);
   }
   return sum;
}
int main() {
   int arr[] = { 2, 3, 5, 4 }, K = 3;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << getSum(arr, K, n) << endl;
}

Output

13
raja
Published on 27-Jul-2020 12:15:08
Advertisements