#628

Maximum Product of Three Numbers

Easy
ArrayMathSortingSortingGreedy
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)

The optimal solution leverages sorting to efficiently find the maximum product of three numbers. By sorting, we can easily access the largest and smallest numbers, which is crucial for handling negative numbers.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array in non-decreasing order.
  2. 2Step 2: Calculate the product of the three largest numbers (last three in the sorted array).
  3. 3Step 3: Calculate the product of the two smallest numbers (first two in the sorted array) and the largest number (last in the sorted array).
  4. 4Step 4: Return the maximum of the two products calculated in steps 2 and 3.
solution.py3 lines
1def maximumProduct(nums):
2    nums.sort()
3    return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])

Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(1) since we are not using any extra space that scales with input size.

  • 1The maximum product can be achieved using either the three largest numbers or two smallest (negative) numbers and the largest number.
  • 2Sorting helps in easily accessing the largest and smallest numbers.

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