LeetCode 0628. Maximum Product of Three Numbers Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0628. Maximum Product of Three Numbers

Description

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

Solution 1: Sorting + Case Analysis

First, we sort the array nums, and then discuss two cases:

  • If nums contains all non-negative or all non-positive numbers, the answer is the product of the last three numbers, i.e., nums[n-1] × nums[n-2] × nums[n-3];
  • If nums contains both positive and negative numbers, the answer could be the product of the two smallest negative numbers and the largest positive number, i.e., nums[n-1] × nums[0] × nums[1], or the product of the last three numbers, i.e., nums[n-1] × nums[n-2] × nums[n-3].

Finally, return the maximum of the two cases.

The time complexity is O(n × log n), and the space complexity is O(log n). Here, n is the length of the array nums.

PythonJavaC++GoTypeScript
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)(code-box)

Solution 2: Single Pass

We can avoid sorting the array by maintaining five variables: mi1 and mi2 represent the two smallest numbers in the array, while mx1, mx2, and mx3 represent the three largest numbers in the array.

Finally, return max(mi1 × mi2 × mx1, mx1 × mx2 × mx3).

The time complexity is O(n), where n is the length of the array. The space complexity is O(1).

PythonJavaC++GoTypeScript
class Solution: def maximumProduct(self, nums: List[int]) -> int: top3 = nlargest(3, nums) bottom2 = nlargest(2, nums, key=lambda x: -x) return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1])(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !