- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

- Related Questions & Answers
- Maximums from array when the maximum decrements after every access in C++ Program
- C++ Program to find array after removal from maximum
- Maximum removal from array when removal time >= waiting time in C++
- Find maximum sum taking every Kth element in the array in C++
- Maximum possible XOR of every element in an array with another array in C++
- Maximum Possible Product in Array after performing given Operations in C++
- Find the Initial Array from given array after range sum queries in C++
- How to access elements from jagged array in C#?
- How to access elements from an array in C#?
- Array sum after dividing numbers from previous?
- Kth smallest element after every insertion in C++
- How do we access elements from the two-dimensional array in C#?
- Maximum Perimeter Triangle from array in C++
- Select the next row after skipping every 2 rows in MySQL
- Maximum possible middle element of the array after deleting exactly k elements in C++