628. Maximum Product of Three Numbers
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)
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);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.