Finding minimum steps to make array elements equal in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a number, num as the only argument. The function should first construct an array of n elements based on the following rule −

arr[i] = (2 * i) + 1;

Therefore, if the input number is 5, then the array should be −

const arr = [1, 3, 5, 7, 9];

Our function is supposed to calculate and return the minimum number of steps it should take so that all the elements of the array become equal.

Let us now define one step −

One valid step consists of choosing any two numbers from the array (distinct numbers) and adding 1 to the first and subtracting 1 from the second.

Therefore, for the above array, the output should look like −

const output = 6;

Example

The code for this will be −

 Live Demo

const num = 5;
const minimumOperations = (num = 1) => {
   if(num === 1){
      return 0;
   };
   let arr = new Array(num);
   let i = 0;
   let res = 0;
   while(i < num){
      arr[i] = (2 * i) + 1;
      if(arr[i] < num) res += num-arr[i];
      i++;
   };
   return res;
};
console.log(minimumOperations(num));

Output

And the output in the console will be −

6
raja
Published on 26-Feb-2021 08:26:26
Advertisements