How to Find Maximum Integer Products using Javascript?


Given an array of non-negative integers, find the maximum integer product of any 3 numbers. For example, [3, 2, 1, 9] the maximum integer product of 3 numbers is 9*3*2=54.

Javascript Solution

Since the numbers are all non-negative, we can sort the numbers (and it works for floating numbers as well) and find the product of the largest 3 numbers. With Javascript, the implementation becomes simple and straightforward with the functional programming concept e.g. reduce.

1
2
3
var findLargestProducts = function(nums, n) {
  return nums.sort((a, b) => (b - a)).slice(0, n).reduce((a, b) => a * b);
}
var findLargestProducts = function(nums, n) {
  return nums.sort((a, b) => (b - a)).slice(0, n).reduce((a, b) => a * b);
}

By default, the array sorting function does not sort numbers by values, but by string representation (alphabetic). For example:

1
[1, 11, 2].sort();// returns [1, 11, 2]
[1, 11, 2].sort();// returns [1, 11, 2]

So, after we feed the sort function with the customize value comparison delegate. We then chain the result with the slice function to get the first few numbers (highest n values), which is reduced to a single value – the product (multiplication result).

Example usage:

1
findLargestProducts([1, 2, 3, 4, 5, 6, 7], 2); // returns 42;
findLargestProducts([1, 2, 3, 4, 5, 6, 7], 2); // returns 42;

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
239 words
Last Post: A Lite Comparison between Linode and Vultr ($5 Basic Plan) Cloud VPS
Next Post: How to Find All Numbers Disappeared in an Array? (C/C++ Coding Exercise)

The Permanent URL is: How to Find Maximum Integer Products using Javascript?

Leave a Reply