Given an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in minimum changes possible.
Input : a[] = {3, 1, 2, 1}
Output : 1
Explanation :
We can convert the array into 3 1 1 1 by
changing 3rd element of array i.e. 2
into its previous integer 1 in one step
hence only one step is required.
Input : a[] = {3, 1, 5, 1}
Output : 4
We need to decrease 5 to 1 to make array sorted
in non-increasing order.
Input : a[] = {1, 5, 5, 5}
Output : 4
We need to increase 1 to 5.
The Solution for this problem I find is given below , but i am unable to understand , I will really appriciate if some one can explain the solution.
class Solution{
public:
int minOperations(int *a,int n)
{
priority_queue<int,vector<int>,greater<int>> q;
int s=0;
for(int i=0;i<n;i++)
{
if(!q.empty() && q.top()<a[i])
{
s=s+(a[i]-q.top());
q.push(a[i]);
q.pop();
}
q.push(a[i]);
}
return s;
}
};