Maximum Product of Three Numbers — LeetCode 628 Python Solution

EasyArrayMathSorting
Problem
#628
Pattern
Sorting
Reading time
2 min

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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview