#1464

Maximum Product of Two Elements in an Array

Easy
ArraySortingHeap (Priority Queue)ArraySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution focuses on finding the two largest numbers in the array. Since the product is maximized when both numbers are as large as possible, we can simply find the two largest numbers and compute the product directly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two variables, first_max and second_max, to track the two largest numbers.
  2. 2Step 2: Iterate through the array to find the two largest numbers.
  3. 3Step 3: Calculate the maximum product using the formula (first_max - 1) * (second_max - 1).
solution.py11 lines
1# Full working Python code
2
3def maxProduct(nums):
4    first_max, second_max = float('-inf'), float('-inf')
5    for num in nums:
6        if num > first_max:
7            second_max = first_max
8            first_max = num
9        elif num > second_max:
10            second_max = num
11    return (first_max - 1) * (second_max - 1)

Complexity note: The time complexity is O(n) because we only need to traverse the array once to find the two largest numbers. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1The product is maximized by selecting the two largest numbers in the array.
  • 2Subtracting 1 from each number before multiplying helps avoid zero products.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.