Find the greatest product of three numbers in JavaScript

In JavaScript, finding the greatest product of three numbers from an array requires considering both positive and negative numbers. This problem has multiple approaches, from brute force to optimized sorting methods.

Understanding the Problem

Given an array of integers, we need to find three numbers whose product is the largest among all possible combinations. For example, with array [1, 5, 3, 2, 4], the three largest numbers (3, 4, 5) give us the product 3 × 4 × 5 = 60.

However, with negative numbers like [-4, -1, 0, 3, 10, 5], the maximum product might be (-4) × (-1) × 10 = 40, not 3 × 5 × 10 = 150, depending on the complete array composition.

Method 1: Sorting Approach

Sort the array and consider the product of the three largest elements:

function findGreatestProduct(nums) {
    // Sort array in ascending order
    const sortedNums = nums.sort((a, b) => a - b);
    const n = sortedNums.length;
    
    // Calculate product of three largest numbers
    const maxProduct = sortedNums[n-1] * sortedNums[n-2] * sortedNums[n-3];
    
    return maxProduct;
}

// Test with positive numbers
const nums1 = [1, 4, 3, 7, 6, 5, 9];
console.log("Array:", nums1);
console.log("Greatest product:", findGreatestProduct(nums1));

// Test with mixed numbers
const nums2 = [-10, -10, 5, 2];
console.log("\nArray:", nums2);
console.log("Greatest product:", findGreatestProduct(nums2.slice()));
Array: [1, 4, 3, 7, 6, 5, 9]
Greatest product: 378

Array: [-10, -10, 5, 2]
Greatest product: 500

Method 2: Optimized Approach for Mixed Numbers

For arrays with negative numbers, we need to consider multiple combinations:

function findGreatestProductOptimized(nums) {
    if (nums.length < 3) return null;
    
    // Sort the array
    nums.sort((a, b) => a - b);
    const n = nums.length;
    
    // Consider two scenarios:
    // 1. Three largest numbers
    const option1 = nums[n-1] * nums[n-2] * nums[n-3];
    
    // 2. Two smallest (if negative) * largest
    const option2 = nums[0] * nums[1] * nums[n-1];
    
    return Math.max(option1, option2);
}

// Test cases
const testCases = [
    [1, 4, 3, 7, 6, 5, 9],
    [-10, -10, 5, 2],
    [-6, -1, 3, 4, 5],
    [1, 2, 3, 4]
];

testCases.forEach((arr, index) => {
    console.log(`Test ${index + 1}: [${arr}]`);
    console.log(`Result: ${findGreatestProductOptimized([...arr])}<br>`);
});
Test 1: [1,4,3,7,6,5,9]
Result: 378

Test 2: [-10,-10,5,2]
Result: 500

Test 3: [-6,-1,3,4,5]
Result: 120

Test 4: [1,2,3,4]
Result: 24

Method 3: Brute Force (All Combinations)

For complete accuracy, especially with complex arrays, check all possible triplets:

function findGreatestProductBruteForce(nums) {
    if (nums.length < 3) return null;
    
    let maxProduct = -Infinity;
    const n = nums.length;
    
    // Check all possible combinations of three numbers
    for (let i = 0; i < n - 2; i++) {
        for (let j = i + 1; j < n - 1; j++) {
            for (let k = j + 1; k < n; k++) {
                const product = nums[i] * nums[j] * nums[k];
                maxProduct = Math.max(maxProduct, product);
            }
        }
    }
    
    return maxProduct;
}

// Test with complex case
const complexArray = [-4, -3, -2, -1, 60];
console.log("Array:", complexArray);
console.log("Brute force result:", findGreatestProductBruteForce(complexArray));
console.log("Optimized result:", findGreatestProductOptimized([...complexArray]));
Array: [-4, -3, -2, -1, 60]
Brute force result: 720
Optimized result: 720

Complexity Comparison

Method Time Complexity Space Complexity Handles Negatives?
Sorting Approach O(n log n) O(1) Partially
Optimized O(n log n) O(1) Yes
Brute Force O(n³) O(1) Yes

Conclusion

The optimized sorting approach works best for most cases, handling negative numbers efficiently with O(n log n) complexity. Use brute force only for small arrays or when you need to verify results.

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

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements