Maximum Product of Two Elements in an Array

Easy

Topics
ArraySorting

Given an array nums, choose two different indices i and j and return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1

30415223
The score is (a-1)(b-1), which still increases with both values, so the two largest elements win: (5−1)(4−1) = 12.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,4,5,2]
Output: 12

Example 2

10514253
Input:  nums = [1,5,4,5]
Output: 16

Constraints

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3
Editorial — intuition, approach, complexity and pitfalls

Intuition

We maximise (nums[i] - 1) * (nums[j] - 1). Since every value is at least 1, both factors are non-negative and increasing either one can only help — so take the two largest values. No case analysis is needed, unlike the three-number version where negatives complicate things.

Sorting gets you there, but to read two values it allocates or reorders the whole array. One pass tracking the top two is O(n) time and O(1) space.

Approach

  1. Track the largest and second largest in one pass.
  2. Return (max1 - 1) * (max2 - 1).

Dry Run

nums = [3,4,5,2]

x=3  max1=3 max2=0
x=4  max1=4 max2=3
x=5  max1=5 max2=4
x=2  no change

answer (5-1)*(4-1) = 12

nums = [1,5,4,5]
x=1 -> 1,0 ; x=5 -> 5,1 ; x=4 -> 5,4 ; x=5 -> 5,5
answer (5-1)*(5-1) = 16     duplicates are two separate elements

Complexity

  • Time — O(n): one pass, against O(n log n) for sorting.
  • Space — O(1): two scalars. sorted(nums) is O(n) because it copies, so the O(1) claim only holds for this version.

Common Pitfalls

  • Updating max2 in a way that loses a duplicate of the maximum. [5,5] must give 16, so the second 5 has to land in max2 — use elif x > max2 with a strict comparison against max1 handled first.
  • Subtracting 1 after multiplying, or once from the product.
  • Initialising the trackers to the first element and starting the loop at index 1 without handling a two-element array. Starting both at 0 works because values are at least 1.
  • Claiming O(1) space while sorting a copy.

Full Solution — all languages

class Solution:
    def maxProduct(self, nums):
        # sorted() would copy the array to read two values; one pass is O(1) space.
        max1 = max2 = 0                 # values are >= 1 by constraint
        for x in nums:
            if x > max1:   max1, max2 = x, max1
            elif x > max2: max2 = x
        return (max1 - 1) * (max2 - 1)
Asked at Samsung
SensAI
Beta
Tap the mic to stop voice mode