Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum number of increment-other operations to make all array elements equal

I am reading this question in geek for geeks site.

The question is about finding the number of minimum moves in an array so all elements are equal.

We are given an array consisting of n elements. At each operation you can select any one element and increase rest of n-1 elements by 1. You have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this.

Examples:

Input : arr[] = {1, 2, 3}
Output : Minimum Operation = 3
Explanation : 
operation | increased elements | after increment
    1     |    1, 2            | 2, 3, 3
    2     |    1, 2            | 3, 4, 3
    3     |    1, 3            | 4, 4, 4

Input : arr[] = {4, 3, 4}
Output : Minimum Operation = 2
Explanation : 
operation | increased elements | after increment
     1    |    1, 2           | 5, 4, 4
     2    |    2, 3           | 5, 5, 5

The link explains we have to use the formula minOperation = sum - (n * small) to get the answer, where sum is the total of all elements in array, n is the number of elements in array and small is the least element in array.

Can you please help me in understanding what the formula indicates minOperation = sum - (n * small)? and how it solves the question?

like image 548
learner Avatar asked Jan 29 '23 22:01

learner


1 Answers

Edit 1: To relate to this solution better, it is good to mention what user Dukeling has said in his comments. That is, increasing all other elements except the largest element is similar to decreasing only the largest element.


Now, imagine you are trying to level many columns of bricks. Each column of bricks can be of different level:

In order to level all column of bricks, you always pick the highest column and remove 1 brick at a time.

Repeat the process till all columns are levelled. enter image description here

Those coloured in yellow are the bricks you need to remove to achieve your goal.(they also mean the number of operations you need to perform to reach your goal)

In order to count number of red bricks, you use a simple formula similar to area of rectangle, that is length x breadth.

min x number of columns = all the red bricks (to be remained untouched)

sum of all bricks - number of red bricks = all yellow bricks 

Hence you have the formula:

minOperation = sum - (n * small) 

enter image description here

Number of yellows = minimum number of operations needed to make all array elements equal.

like image 51
user3437460 Avatar answered Jan 31 '23 14:01

user3437460