
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximums from Array When the Maximum Decrements After Every Access in C++
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
#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