Maximum Product of Two Elements in an Array Problem
#1464
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1464.
You are given an array of integers nums.
Choose two different indices i and j of that array.
Return the maximum value of (nums[i] - 1) * (nums[j] - 1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 5001 <= nums[i] <= 10^3
Solution
Approach: Track the Two Largest Values
All values are at least 1, so nums[i] - 1 is never negative, and the product grows with both factors. The best choice is therefore the two largest numbers in the array (possibly equal values at different indices, as in [1,5,4,5]).
Scan the array once and keep first >= second, the two largest values seen so far:
- If
x > first, the oldfirstbecomessecondandxbecomesfirst. - Otherwise, if
x > second,xreplacessecond.
Return (first - 1) * (second - 1). Because a repeated maximum goes to the else branch only when it is not larger than first, the second copy of 5 in [1,5,4,5] still becomes second.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxProduct(self, nums: List[int]) -> int:
first = second = 0 # the two largest values seen so far, first >= second
for x in nums:
if x > first:
first, second = x, first
elif x > second:
second = x
return (first - 1) * (second - 1)