

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Greatest sum and smallest index difference in JavaScript
Problem
JavaScript function that takes in an array of Integers, arr, as the first and the only argument.
Our function should pick an index pair (i, j) such that (arr[i] + arr[j]) + (i - j) is maximum amongst all index pairs in the array. Our function should then return the maximum value.
For example, if the input to the function is −
const arr = [8, 1, 5, 2, 6];
Then the output should be −
const output = 11;
Output Explanation
Because if we choose i = 0 and j = 2 then the value will be −
(8 + 5) + (0 - 2) = 11
Which is indeed maximum for any index pair.
Example
The code for this will be −
const arr = [8, 1, 5, 2, 6]; const findMaximum = (arr = []) => { let max = arr[0] + 0; let res = -Infinity; for(let i = 1; i < arr.length; i++){ res = Math.max(res, max + arr[i] - i); max = Math.max(arr[i] + i, max); }; return res; }; console.log(findMaximum(arr));
Output
And the output in the console will be −
11
- Related Questions & Answers
- Finding difference of greatest and the smallest digit in a number - JavaScript
- Smallest possible length constituting greatest frequency in JavaScript
- Greatest sum of average of partitions in JavaScript
- Path with smallest sum in JavaScript
- Finding the greatest and smallest number in a space separated string of numbers using JavaScript
- Even index sum in JavaScript
- Finding smallest sum after making transformations in JavaScript
- Maximum sum of smallest and second smallest in an array in C++
- Odd even index difference - JavaScript
- Index difference of tuples in JavaScript
- Greatest Sum Divisible by Three in C++
- Difference between Inverted Index and Forward Index
- Difference between sum of square and square of sum in JavaScript
- Cumulative sum at each index in JavaScript
- Maximum sum of smallest and second smallest in an array in C++ Program
Advertisements