EasyNo. 0628
Maximum Product of Three Numbers — LeetCode 628 Python Solution
- Pattern
- Sorting
- Topics
- Array, Math, 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
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
- Time
- O(n × log n)
- Space · auxiliary
- O(log n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0462 | Minimum Moves to Equal Array Elements II | Medium |
| 0539 | Minimum Time Difference | Medium |
| 0891 | Sum of Subsequence Widths | Hard |
| 1030 | Matrix Cells in Distance Order | Easy |
| 1840 | Maximum Building Height | Hard |
| 2033 | Minimum Operations to Make a Uni-Value Grid | Medium |
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 × 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.