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.
1function maxProduct(nums) {
2 nums.sort((a, b) => a - b);
3 const n = nums.length;
4 return (nums[n - 1] - 1) * (nums[n - 2] - 1);
5}
6
7console.log(maxProduct([3, 4, 5, 2]));
In JavaScript, the sort()
function is used with a comparator to sort the array numerically. The resulting maximum product is then calculated from the last two elements, post decrement.
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.
In Python, the two maximums are determined by tracking the largest and second-largest numbers during a single traversal of the list. This process avoids the need to sort and efficiently produces the maximum product.