

- 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
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]
- Related Questions & Answers
- Finding the product of array elements with reduce() in JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding product of an array using recursion in JavaScript
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- Finding product of Number digits in JavaScript
- Finding the largest prime factor of a number in JavaScript
- Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript
- Largest Palindrome Product in C++
- Finding special array - JavaScript
- Constructing product array in JavaScript
- Return the largest array between arrays JavaScript
- Finding the largest 5 digit number within the input number using JavaScript
- Finding the group with largest elements with same digit sum in JavaScript
- Finding the maximum in a nested array - JavaScript
- Finding the rotation of an array in JavaScript
Advertisements