




Sponsored
Sponsored
This approach involves sorting the array, and then choosing the maximum product by examining either the product of the three largest numbers or the product of the two smallest numbers and the largest number.
Time Complexity: O(n log n) due to sorting. 
 Space Complexity: O(1) as we use in-place sorting.
1import java.util.Arrays;
2
3public class MaxProduct {
4    public static int maximumProduct(int[] nums) {
5        Arrays.sort(nums);
6        int n = nums.length;
7        return Math.max(nums[n-1] * nums[n-2] * nums[n-3], nums[0] * nums[1] * nums[n-1]);
8    }
9    public static void main(String[] args) {
10        int[] nums = {1, 2, 3, 4};
11        System.out.println(maximumProduct(nums));
12    }
13}After sorting the array, we compute the products of the three largest and the two smallest elements with the largest element, then return the maximum of the two values.
This approach involves finding the largest three and smallest two numbers in a single traversal of the array. This avoids sorting and gives a more optimal solution for time complexity.
Time Complexity: O(n) as there's only a single pass through the array. 
 Space Complexity: O(1).
1#
We maintain variables for the three largest and two smallest numbers as we iterate. This allows us to compute the potential maximum products and choose the maximum one without needing to sort the array.