Maximum Product of Two Elements in an Array (LeetCode 1464): Solution and Explanation
Choose two different indices and maximise (nums[i] - 1) * (nums[j] - 1). Because every value is at least 1, the answer always comes from the two largest values.
Intuition
Every number is at least 1, so each factor nums[i] - 1 is zero or positive. With no negative factors around, making either factor larger can only make the product larger.
That means the best pair is simply the largest value and the second largest value. Duplicates are fine: two copies of the maximum at different indices count as two values.
Sorting finds them, but you only need two numbers, so one pass with two slots is enough. Think of a leaderboard with a gold and a silver spot.
Approach: One pass with first and second
- Set
first = second = 0. - For each
xinnums: ifx > first, movefirstintosecondand setfirst = x. - Otherwise, if
x > second, setsecond = x. - Return
(first - 1) * (second - 1).
Step-by-step example
nums = [3,4,5,2]
- x = 3 beats the empty first slot: first = 3, second = 0.
- x = 4 beats first: 3 drops to second, first = 4.
- x = 5 beats first: 4 drops to second, first = 5.
- x = 2 does not beat second (4), so nothing changes.
- Return (5 - 1) * (4 - 1) = 12.
Code: Python, Java, C++
1class Solution:
2 def maxProduct(self, nums: List[int]) -> int:
3 first = second = 0
4 for x in nums:
5 if x > first:
6 first, second = x, first
7 elif x > second:
8 second = x
9 return (first - 1) * (second - 1)1class Solution {
2 public int maxProduct(int[] nums) {
3 int first = 0, second = 0;
4 for (int x : nums) {
5 if (x > first) {
6 second = first;
7 first = x;
8 } else if (x > second) {
9 second = x;
10 }
11 }
12 return (first - 1) * (second - 1);
13 }
14}1class Solution {
2public:
3 int maxProduct(vector<int>& nums) {
4 int first = 0, second = 0;
5 for (int x : nums) {
6 if (x > first) {
7 second = first;
8 first = x;
9 } else if (x > second) {
10 second = x;
11 }
12 }
13 return (first - 1) * (second - 1);
14 }
15};Time and space complexity
O(n)
Each element is compared with at most two slots once.
O(1)
Only the two slot variables are stored.
Other approaches
Sort and take the last two (time O(n log n), space O(1))
Sort ascending and return (nums[n-1] - 1) * (nums[n-2] - 1). One line, but the sort costs more than a scan.
Min-heap of size two (time O(n), space O(1))
Push each value into a min-heap and pop when it holds more than two. The heap keeps the two largest. It generalises to the k largest values.
Common mistakes
- Overwriting first without moving its old value into second. When a new maximum arrives, the old maximum becomes the runner-up.
- Skipping a duplicate maximum. In [1,5,4,5] the answer uses both 5s, so a repeat of first must still be able to become second.
- Trying all pairs with two loops. It works for n <= 500 but misses the observation that makes the problem trivial.
Frequently asked questions
Would this still work if negative numbers were allowed?
Not directly. Two very negative values give two negative factors whose product is positive and possibly larger, so you would also need to check the two smallest values.
Why does a duplicate of the maximum count?
The indices must differ, not the values. Two different positions holding the same maximum are a valid pair, and the scan places the second copy in the second slot.
Why start the slots at 0?
Every input value is at least 1, so any real value beats 0 and fills the slot on first sight.