Largest difference between element with a twist in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers. The function should find the difference between the largest and the smallest element of the array.

The condition is that the element which is smaller should appear before the greater element in the original array.

For example −

Consider the following array of Numbers −

const arr = [2, 5, 6, 12, 1];

For this array, our function should output 10.

Although the greatest and the smallest elements of the array are 12 and 1 respectively, since 1 does not appear before 12, we cannot consider it a valid smaller number for the purpose of this question.

Therefore, our function returns the difference −

12 - 2 = 10

Example

Following is the code −

const arr = [2, 5, 6, 12, 1];
const findLargestDifference = (arr = []) => {
   if (arr.length <= 1){
      return -1;
   };
   let min = arr[0];
   let diff = 0;
   for (let i = 1; i < arr.length; i++) {
      if (arr[i] > min && (arr[i] - min > diff)) {
         diff = arr[i] - min;
      }
      else if (arr[i] <= min) {
         min = arr[i];
      }
   }
   if (diff <= 0){
      return -1
   };
   return diff;
};
console.log(findLargestDifference(arr));

Output

Following is the output on console −

10
raja
Published on 10-Dec-2020 12:42:43
Advertisements