
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
Finding the Largest Triple Product Array in JavaScript
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]