#3732

Maximum Product of Three Elements After One Replacement

Medium
ArrayMathGreedySortingSortingGreedy
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(1)

Identify the two largest and the two smallest numbers. Replace the smallest with 10^5 to maximize the product.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the two largest and two smallest numbers in the array.
  2. 2Step 2: Calculate the product of the two largest numbers with 10^5.
  3. 3Step 3: Calculate the product of the two smallest numbers with 10^5 (for negative scenarios) and return the maximum of both products.
solution.py3 lines
1def maxProduct(nums):
2    nums.sort()
3    return max(nums[-1] * nums[-2] * 100000, nums[0] * nums[1] * 100000)

Complexity note: Sorting the array takes O(n log n), while finding the maximum product is O(1).

  • 1Replacing with 10^5 can maximize product when combined with large negatives.
  • 2Sorting helps quickly identify the largest and smallest values.

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