Skip to content

628. Maximum Product Of Three Numbers

Array Math Sorting

Problem - Maximum Product Of Three Numbers

Easy

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

 

Example 1:

Input: nums = [1,2,3]
Output: 6

Example 2:

Input: nums = [1,2,3,4]
Output: 24

Example 3:

Input: nums = [-1,-2,-3]
Output: -6

 

Constraints:

  • 3 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        largest = nlargest(3, nums)
        smallest = nlargest(2, nums, key=lambda x: -x)
        return max(largest[0] * largest[1] * largest[2], largest[0] * smallest[0] * smallest[1])

        # nums.sort()
        # val1 = nums[-1] * nums[-2] * nums[-3]
        # val2 = nums[-1] * nums[0] * nums[1]
        # return max(val1, val2)

Submission Stats:

  • Runtime: 12 ms (75.65%)
  • Memory: 18.6 MB (60.44%)