Leetcode 628. Maximum Product of Three Numbers
Given an integer array nums
, find three numbers whose product is maximum and return the maximum product.
nums
?
nums[len-1] * nums[len-2] * nums[len-3]
.nums[0] * nums[1] * nums[len-1]
.public class Solution {
public int maximumProduct(int[] nums) {
// Sort the array
Arrays.sort(nums);
int n = nums.length;
// Candidate 1: product of the three largest numbers
int candidate1 = nums[n-1] * nums[n-2] * nums[n-3];
// Candidate 2: product of the two smallest numbers and the largest number
int candidate2 = nums[0] * nums[1] * nums[n-1];
// Return the maximum of the two candidates
return Math.max(candidate1, candidate2);
}
}
O(n log n)
where n
is the length of the array.O(1)
constant time operation.Therefore, the overall time complexity is O(n log n)
due to sorting.
This method ensures that we correctly identify the maximum product by considering both positive and negative numbers efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?