Finding smallest sum after making transformations in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of positive integers. We can transform its elements by running the following operation on them as many times as required −

if arr[i] > arr[j] then arr[i] = arr[i] - arr[j]

When no more transformations are possible, our function should return its sum.

Example

Following is the code −

 Live Demo

const arr = [6, 9, 21];
const smallestSum = (arr = []) => {
   const equalNums = arr => arr.reduce((a, b) => {
      return (a === b) ? a : NaN;
   });
   if(equalNums(arr)){
      return arr.reduce((a, b) => {
         return a + b;
      });
   }else{
      const sorted = arr.sort((a, b) => {
         return a-b;
      });
      const last = sorted[arr.length-1] - sorted[0]
      sorted.pop();
      sorted.push(last);
      return smallestSum(sorted);
   };
};
console.log(smallestSum(arr));

Output

Following is the console output −

9

Updated on: 19-Apr-2021

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements