↓Skip to main content
  1. LeetCode/

LeetCode 628: Maximum Product of Three Numbers

·1 min· ·
LeetCode Easy Array Math Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-29

  • Submissions: Wrong Answer → Accepted ×3

Approach
#

Only two cases can give the largest product of three (Math Template 4): the three largest values, or the two smallest (possibly large negatives, whose product is positive) times the largest. Sort and take the larger of the two; no case split on signs is needed.

My Attempts
#

Attempt 1 mistyped an index as nums[-1] * nums[-1] * nums[-2], using the largest number twice: [6, 5, 7] returned 294 instead of 210. It also had an unneeded branch on whether any number is positive.

Solution
#

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        nums.sort()
        return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])

Complexity
#

Time O(n log n), space O(1); tracking the top three and bottom two gives O(n).

Mistakes to Avoid
#

  • Two negatives multiply to a positive, so the two smallest are candidates too.
  • Get the indices right: nums[-1] * nums[-2] * nums[-3].

Interview Explanation
#

After sorting the answer is either the three largest or the two smallest times the largest, whichever is bigger. Time O(n log n); one pass tracking the top three and bottom two gives O(n).

Related

LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 598: Range Addition II
·2 mins
LeetCode Easy Array Math
LeetCode 598 note: every operation covers the top-left corner, so the most-incremented cells form the intersection of all operations: min(a) × min(b)
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 414: Third Maximum Number
·1 min
LeetCode Easy Array Sorting
LeetCode 414 note: track the three largest distinct values, skipping repeats, and return the maximum if fewer than three distinct values exist
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0