Make all array elements equal to K by repeatedly incrementing subsequences

Given an array arr[] consisting of N integers and an integer K, the task is to make all array elements equal to K by repetedly incrementing all elements of subsequences by 1.Note: The value of K is at least the maximum element of the array.
Examples:

Input: arr[] = {2, 3, 3, 4}, K = 5Output: 4Explanation:Operation 1: Select the subsequence {2, 3, 4}. After incrementing each element, the subsequence modifies to {3, 4, 5}. The array modifies to {3, 3, 4, 5}.Operation 2: Select the subsequence {3, 4}. After incrementing each element, the subsequence modifies to {4, 5}. The array modifies to {3, 4, 5, 5}.Operation 3: Select the subsequence {3, 4}. After incrementing each element, the subsequence modifies to {4, 5}. The array modifies to {4, 5, 5, 5}.Operation 4: Select the subsequence {4}. After incrementing each element, the subsequence modifies to {5}.The array modifies to {5, 5, 5, 5}.
Input: arr[] = {1, 1, 1, 1}, K = 3Output: 5

Approach: The idea is to use Hashing to keep track of the elements in the subsequences. When an element in a subsequence is increased by 1, its frequency reduces by 1 and the frequency of its modified value increases by 1.Follow the steps below to solve the problem:Initialize a variable, say ans, that stores the minimum number of operations required.
Initialize a Hashmap, say mp, and store the frequency of array elements.
While the frequency of K is less than N, i.e., mp[K] < N, perform the following operations: Iterate through a range [1, K – 1] using the variable i If mp[i] is greater than 0, decrease the frequency of the current value and increase the frequency of the next group (i + 1) elements by 1. If (i + 1) is not part of any previous value, skip it and continue traversing the loop. Increment the value of ans by 1. After completing the above steps, print the value of ans as the result. Below is the implementation of the above approach: C++    #include using namespace std;    void minOperations(int arr[], int n, int k) {          map mp;             for (int i = 0; i < n; i++) {         mp[arr[i]]++;     }                  int ans = 0;                  while (mp[k] < n) {                                       for (int i = 1; i