Largest index difference with an increasing value in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr. Our function should return the largest difference in indexes j - i such that arr[i] <= arr[j]

Example

The code for this will be −

 Live Demo

const arr = [1, 2, 3, 4];
const findLargestDifference = (arr = []) => {
   const { length: len } = arr;
   let res = 0;
   for(let i = 0; i < len; i++){
      for(let j = i + 1; j < len; j++){
         if(arr[i] <= arr[j] && (j - i) > res){
            res = j - i;
         };
      };
   };
   return res;
};
console.log(findLargestDifference(arr));

Output

And the output in the console will be −

3

Updated on: 17-Apr-2021

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements