LeetCode 628: Maximum Product of Three Numbers Solution
Master LeetCode problem 628 (Maximum Product of Three Numbers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To find the maximum product of three numbers in the given array, we can sort the array and consider two cases:
- The product of the three largest numbers (if there are positive numbers in the array).
- The product of the two smallest numbers (which will be negative) and the largest number (to account for negative numbers in the array).
By comparing these two cases, we can determine the maximum product of three numbers.
- Sort the input array.
- Calculate the products of the two smallest numbers and the largest number, and the product of the three largest numbers.
- Return the maximum of these two products.
Time complexity: O(nlogn) due to sorting the input array. Space complexity: O(1)
Solution Code
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int option1 = nums[n-1] * nums[n-2] * nums[n-3];
int option2 = nums[0] * nums[1] * nums[n-1];
return Math.max(option1, option2);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 628 (Maximum Product of Three Numbers)?
This page provides optimized solutions for LeetCode problem 628 (Maximum Product of Three Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 628 (Maximum Product of Three Numbers)?
The time complexity for LeetCode 628 (Maximum Product of Three Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 628 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 628 in Java, C++, or Python.