Return the greatest possible product of n numbers from the array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n, as the second argument.

Our function should calculate and return the greatest possible product of n numbers from the array.

Problem Analysis

To find the maximum product of n numbers, we need to consider both positive and negative numbers. Two negative numbers multiplied together give a positive result, so the strategy involves:

  • Sorting the array to identify the largest and smallest values
  • Choosing pairs that give the maximum product
  • Handling odd values of n by selecting the largest remaining number

Solution

const getHighestProduct = (arr, num) => {
    let prod = 1;
    const sorter = (a, b) => a - b;
    arr.sort(sorter);
    
    // Check if num is greater than array length or invalid case
    if (num > arr.length || num & 2 && arr[arr.length - 1] < 0) {
        return;
    };
    
    // If num is odd, take the largest element first
    if (num % 2) {
        prod = arr.pop();
        num--;
    };
    
    // Process pairs to maximize product
    while (num) {
        prod *= arr[0] * arr[1] > arr[arr.length - 2] * arr[arr.length - 1]
        ? arr.shift() * arr.shift() : arr.pop() * arr.pop();
        num -= 2;
    };
    
    return prod;
}

console.log(getHighestProduct([1, 10, -5, 1, -100], 3));
console.log(getHighestProduct([3, 4, 5, 6, 7], 3));
console.log(getHighestProduct([3, 4, -5, -6, -7], 3));

Output

5000
210
168

How It Works

The algorithm works by:

  1. Sorting: Array is sorted in ascending order to easily identify extreme values
  2. Odd handling: If n is odd, the largest positive number is selected first
  3. Pair selection: Compares products from both ends of the sorted array to choose the maximum
  4. Greedy approach: Always picks the pair that gives the larger product

Example Breakdown

For [1, 10, -5, 1, -100] with n=3:

  • Sorted: [-100, -5, 1, 1, 10]
  • n is odd, so take largest: prod = 10, remaining: [-100, -5, 1, 1]
  • Compare pairs: (-100) × (-5) = 500 vs 1 × 1 = 1
  • Choose 500, final result: 10 × 500 = 5000

Conclusion

This solution efficiently finds the maximum product by leveraging sorting and greedy selection. It handles both positive and negative numbers by comparing products from array extremes.

Updated on: 2026-03-15T23:19:00+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements