Introduction
Finding the maximum product of three numbers in an array is a common problem in programming. This task can be efficiently solved using sorting and a few simple arithmetic operations. This blog will guide you through solving this problem in Java.
Problem Description
Given an integer array nums
, find three numbers whose product is maximum and return the product.

Approach
To solve this problem, we can use sorting. By sorting the array, we can easily identify the three largest numbers, as well as the two smallest numbers. This is crucial because the product of two negative numbers can be positive and large.
Steps
- Sort the array.
- The maximum product will be the maximum of:
- The product of the three largest numbers.
- The product of the two smallest numbers (which could be negative) and the largest number.

Java Solution
Here’s a sample Java implementation:
import java.util.Arrays;
public class MaximumProduct {
public static int maximumProduct(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
// Maximum product of three largest numbers
int max1 = nums[n - 1] * nums[n - 2] * nums[n - 3];
// Maximum product of two smallest numbers and the largest number
int max2 = nums[0] * nums[1] * nums[n - 1];
// Return the maximum of the two
return Math.max(max1, max2);
}
public static void main(String[] args) {
int[] nums = {-10, -10, 5, 2};
System.out.println("Maximum product of three numbers: " + maximumProduct(nums)); // Output: 500
}
}
Explanation
- Sorting: We start by sorting the array.
- Calculating Products: We then calculate two potential maximum products:
- The product of the three largest numbers.
- The product of the two smallest numbers and the largest number.
- Returning the Result: Finally, we return the larger of the two products.

Conclusion
This approach ensures that we cover all possible cases, including those with negative numbers. By sorting the array and using basic arithmetic operations, we can efficiently find the maximum product of three numbers in O(n log n) time complexity. This solution is both simple and effective for tackling the problem.
Feel free to try this code and explore further optimizations or variations for different scenarios!
Read More …
Graph Data Structure – https://kamleshsingad.com/graph-data-structure/
Development of a 3D Printer: A Step-by-Step Project – https://kamleshsingad.com/development-of-a-3d-printer/
Introduction to SQL Programming: A Beginner’s Guide – https://kamleshsingad.com/introduction-to-sql-programming-a-beginners-guide/