Maximum Product of Three Numbers
Given an integer array nums, find the maximum product of any three numbers from the array. The array may contain negative numbers, so the maximum product could be either the product of the three largest numbers or the product of the two smallest negatives times the largest positive.
Sort the array. The answer is max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]). The first candidate handles all-positive or mixed arrays where the three largest give the max product. The second handles cases where two very negative numbers produce a large positive when multiplied together and then by the largest positive.
Time is O(n log n) for sorting, space O(1). A linear O(n) approach is also possible but sorting is simpler for this difficulty level.
Edge cases include all negative numbers (product of three largest/least negative), zeros in the array leading to zero product, and duplicate values.
The two-candidate approach works because for any sorted array, the maximum product of three is either the three largest numbers (if all positive or all negative) or two negatives times the largest positive (which becomes positive). The two candidate formulas capture all scenarios: the three largest numbers work when negatives aren't involved, while two negatives times the largest positive captures cases where multiplying two negatives yields a positive product that exceeds the three largest positives.Example Input & Output
2*3*4=24.
(-5)*(-4)*3=60.
1*1*1=1.
-1*-2*-3=-6.
1*2*3=6.
Algorithm Flow

Solution Approach
Sort array. Take max of (largest3 product) and (smallest2 * largest1 product).
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums) {
Arrays.sort(nums);
int n=nums.length;
return Math.max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
