Finding the Largest Triple Product Array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of integers as the only argument.

Based on the array taken in as input, the function should construct a new array of the same length based on the following criteria.

Any corresponding element of the output array should be the product of the three largest numbers encountered thus far. If the corresponding index is less than 3 (we have not encountered three elements yet) then the corresponding value should be -1. And Although we can use non-unique values to calculate the product, but those non-unique values should be present at different indices.

For example −

If the input array is −

const arr = [1, 2, 3, 4, 5, 6];

Then the output should be −

const output = [-1, -1, 6, 24, 60, 120];

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6];
const maximumTripleProduct = (arr = []) => {
   const res = [];
   const max = [arr[0], arr[1], arr[2]];
   res[0] = res[1] = -1;
   res[2] = arr[0] * arr[1] * arr[2];
   for(let i = 3; i < arr.length; i++){
      max.push(arr[i]);
      max.sort((a, b) => b - a);
      max.pop();
      res[i] = max[0] * max[1] * max[2];
   };
   return res;
};
console.log(maximumTripleProduct(arr));

Output

Following is the console output −

[-1, -1, 6, 24, 60, 120]
raja
Published on 27-Jan-2021 06:22:46
Advertisements