Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements