
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Finding difference of greatest and the smallest digit in a number - JavaScript
- Smallest possible length constituting greatest frequency in JavaScript
- Path with smallest sum in JavaScript
- Greatest sum of average of partitions in JavaScript
- Even index sum in JavaScript
- Explain the greatest and the smallest comparing numbers.
- Finding the greatest and smallest number in a space separated string of numbers using JavaScript
- Finding smallest sum after making transformations in JavaScript
- Cumulative sum at each index in JavaScript
- Index difference of tuples in JavaScript
- Odd even index difference - JavaScript
- Reverse index value sum of array in JavaScript
- Common element with least index sum in JavaScript
- Write the smallest and the greatest number: $30900,\ 30594,\ 30495,\ 30945$.
- Difference between sum of square and square of sum in JavaScript

Advertisements