Maximum Product of Three Numbers — LeetCode 628 Python Solution
EasyArrayMathSorting
- Problem
- #628
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example
- Input
- nums = [1,2,3]
- Output
- 6
Python solution
Python
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
a = nums[-1] * nums[-2] * nums[-3]
b = nums[-1] * nums[0] * nums[1]
return max(a, b)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 628. Maximum Product of Three Numbers is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 628. Maximum Product of Three Numbers?
- LeetCode 628. Maximum Product of Three Numbers is rated Easy on LeetCode.
- What is the time complexity of LeetCode 628. Maximum Product of Three Numbers?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 628. Maximum Product of Three Numbers?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 628. Maximum Product of Three Numbers cover?
- LeetCode 628. Maximum Product of Three Numbers is tagged Array, Math and Sorting on LeetCode.