Given the array nums
, consisting of positive integers, find the maximum product of two elements in the array leveraging the specified rule. Specifically, you need to return the product of the two largest elements in the list, each decreased by 1. Formally, the task is to find max((nums[i]-1) * (nums[j]-1)) where 0 <= i < j < nums.length.
Input: nums = [3,4,5,2]
Output: 12
Explanation: (5-1) * (4-1) = 4 * 3 = 12.
Input: nums = [1,5,4,5]
Output: 16
Explanation: (5-1) * (5-1) = 4 * 4 = 16.
Input: nums = [3,7]
Output: 12
(largest-1) * (secondLargest-1)
.def maxProduct(nums):
first_max = second_max = -1
for num in nums:
if num > first_max:
second_max = first_max
first_max = num
elif num > second_max:
second_max = num
return (first_max - 1) * (second_max - 1)
# Testing the function with given examples
print(maxProduct([3,4,5,2])) # Output: 12
print(maxProduct([1,5,4,5])) # Output: 16
print(maxProduct([3,7])) # Output: 12
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?