Sponsored
Sponsored
One effective way to find the maximum product is by first sorting the array, then selecting the two largest elements, which will naturally be at the end of the sorted list. The product of their decremented values will provide the result.
Time Complexity: O(n^2) due to the bubble sort implementation. Space Complexity: O(1) since no extra space is used.
1import java.util.Arrays;
2
3public class Solution {
4 public int maxProduct(int[] nums) {
5 Arrays.sort(nums);
6 int n = nums.length;
7 return (nums[n-1] - 1) * (nums[n-2] - 1);
8 }
9 public static void main(String[] args) {
10 Solution solution = new Solution();
11 int[] nums = {3, 4, 5, 2};
12 System.out.println(solution.maxProduct(nums));
13 }
14}
In Java, the Arrays.sort()
method is used for sorting. After sorting, the code identifies the last two numbers to compute the maximum product when reduced by one each.
This approach finds the two largest numbers in a single pass without sorting. By iterating over the array, we track the largest and second-largest numbers. With these two numbers, we compute the maximum product efficiently.
Time Complexity: O(n) because we pass through the array just once. Space Complexity: O(1) as no additional space is required.
1
The C implementation maintains two variables to track the largest and second-largest numbers encountered. Each element is compared in sequence, and the variables are adjusted appropriately to find these numbers without sorting the full array.