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.
1def max_product(nums):
2 nums.sort()
3 return (nums[-1] - 1) * (nums[-2] - 1)
4
5print(max_product([3, 4, 5, 2]))
Python's solution utilizes the built-in sort()
method to sort the list and calculates the product for the last two elements after decrementing them.
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
public class Solution {
public int MaxProduct(int[] nums) {
int max1 = 0, max2 = 0;
foreach (int num in nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
}
return (max1 - 1) * (max2 - 1);
}
public static void Main() {
int[] nums = {3, 4, 5, 2};
Solution sol = new Solution();
Console.WriteLine(sol.MaxProduct(nums));
}
}
The C# solution tracks the two largest numbers iteratively with straightforward logic stacking comparisons inside a loop. Upon completion, a maximized product of the subtracted values is returned.