Maximum Product of Two Elements in an Array (LeetCode 1464): Solution and Explanation

Easy
Array
Sorting
Heap Priority Queue

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

  1. Set first = second = 0.
  2. For each x in nums: if x > first, move first into second and set first = x.
  3. Otherwise, if x > second, set second = x.
  4. Return (first - 1) * (second - 1).

Step-by-step example

nums = [3,4,5,2]
  1. x = 3 beats the empty first slot: first = 3, second = 0.
  2. x = 4 beats first: 3 drops to second, first = 4.
  3. x = 5 beats first: 4 drops to second, first = 5.
  4. x = 2 does not beat second (4), so nothing changes.
  5. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
One pass with first and second O(n)
Min-heap of size two O(n)
Sort and take the last two O(n log n)
Time

O(n)

Each element is compared with at most two slots once.

Space

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.