Maximum Product of Two Elements in an Array
Given the array of integers nums, find the two distinct indices i and j such that (numsi - 1) * (numsj - 1) is maximized and return that product. The best product always comes from the two largest values in the array, so find them in a single pass.
Constraints
- 2 ≤ nums.length ≤ 500
- 1 ≤ numsi ≤ 103
Example
nums = [3, 4, 5, 2]12Explanation The two largest values are 5 and 4, giving (5-1) * (4-1) = 4 * 3 = 12.
Track the two largest values in one pass
value=3. first=3 (was 0), second=0.
What happens in this step
value = nums[0] = 3 3 > first (0) first becomes 3, second stays 0.
Steps to visualize
- Keep two trackers, first and second, for the largest and second-largest values seen.
- For each value, if it beats first, shift first down to second and set this as the new first.
- Otherwise, if it beats second, update second.
- After scanning the whole array, compute (first - 1) * (second - 1).
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
value=3. first=3 (was 0), second=0.
What happens in this step
value = nums[0] = 3 3 > first (0) first becomes 3, second stays 0.
Solution
function maxProduct(nums) {
let first = 0;
let second = 0;
for (const value of nums) {
if (value > first) {
second = first;
first = value;
} else if (value > second) {
second = value;
}
}
return (first - 1) * (second - 1);
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [3, 4, 5, 2] | 12 | example from the docstring |
nums = [1, 5] | 0 | smallest valid input, one value is the minimum possible |
nums = [3, 3, 3] | 4 | every value identical |
nums = [10, 2] | 9 | boundary case, exactly two elements |
nums = [1, 2, 3] | 2 | ascending values with the top two adjacent |
nums = [9, 9, 3, 4] | 64 | the two largest values are tied |