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
Java implementation uses a for-each loop to navigate through the nums array while keeping track of the largest and second-largest values found so far to compute the maximum product effectively at the end.