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


In this problem, we are given an array arr[] of N integers and an integer m. Our task is to create a program to find the maximums from array when the maximum decrements after every access.

Problem Description − We need to find the maximum sum of maximum elements of the array and decrease the max taken by one k times.

Let’s take an example to understand the problem,

Input

arr[] = {3, 6, 7, 8, 8}, k = 3

Output

Explanation

First iteration: array before = {3, 6, 7, 8, 8}, max = 8, sum = 8, array after update = {3, 6, 7, 7, 8}
Second iteration: array before = {3, 6, 7, 7, 8}, max = 8, sum = 8 + 8 = 16, array after update = {3, 6, 7, 7, 7}
Third iteration: array before = {3, 6, 7, 7, 7}, max = 7, sum = 16 + 7 = 23, array after update = {3, 6, 6, 7, 7}
Maximum sum = 23

Solution Approach

The idea is to find the maximum of the array and then decrement it after adding to maxSum. Repeating this process k times gives the result.

For finding the maximum element of the array, there can be multiple ways and the most promising one is using the max heap data structure.

So, we will insert all the elements of the array to a max heap, the maximum element in the heap is represented at the root of it. We will remove it, add to the maxSum and insert (element -1) back to the heap. Do this k times to get the desired maxSum.

Algorithm

Initialize − maxSum = 0

Step 1 − Create a max heap data structure and push elements to it.

Step 2 − Loop for i -> 0 to k and follow set 3 - 5.

Step 3 − Take the root element, maxVal = root and pop it.

Step 4 − Add maxVal to maxSum, maxSum += maxVal

Step 5 − Insert updated maxVal to the max heap.

Step 6 − Return the maxSum.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
long calcMaxSumDec(int arr[], int m, int n) {
   long maxSum = 0;
   long maxVal;
   priority_queue<long> max_heap;
   for (int i = 0; i < n; i++) {
      max_heap.push(arr[i]);
   }
   for(int i = 0; i < m; i++) {
      maxVal = max_heap.top();
      maxSum += maxVal;
      max_heap.pop();
      max_heap.push(maxVal - 1);
   }
   return maxSum;
}
int main() {
   int arr[] = { 2, 3, 5, 4 }, m = 3;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximums from array when the maximum decrements after every access is    "<<calcMaxSumDec(arr, m, n);
}

Output

The maximums from array when the maximum decrements after every access is 13

Updated on: 22-Dec-2020

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements