Computer >> Computer tutorials >  >> Programming >> Javascript

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