Similar Problems
Similar Problems not available
Maximum Product Of Three Numbers - Leetcode Solution
LeetCode: Maximum Product Of Three Numbers Leetcode Solution
Difficulty: Easy
Problem Statement: 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
Approach: The solution is quite easy to implement. What we need to do is to look for the highest three numbers by value and the two lowest numbers by value (in case of negative numbers). Then we calculate two potential results:
- using the three highest numbers
- using one lower number and two higher numbers
Then we return the highest result obtained.
Solution:
First, we define our function maxProductThreeNumbers:
class Solution: def maximumProduct(self, nums: List[int]) -> int:
nums.sort(reverse=True)
# Function to calculate max product of three numbers
def maxProductThreeNumbers(n):
return max(n[0]*n[1]*n[2],
n[0]*n[-1]*n[-2])
return maxProductThreeNumbers(nums)
Here we first sort the given array nums in descending order. Then, we define a function maxProductThreeNumbers that calculates the maximum product of three numbers in the given array. We then return the maximum product of the three numbers using the two different cases we discussed earlier.
Let’s understand how the above code works.
We first sort the given array nums in descending order which makes n[0] the highest number of the sorted array and n[-1] the lowest number of the sorted array.
We then define the function maxProductThreeNumbers that takes the sorted array n as an argument. Inside this function, we calculate two potential results:
The first potential result is the maximum product of three numbers which is simply n[0] * n[1] * n[2].
The second potential result is the maximum product of two highest numbers and the lowest number. We calculate this product as (n[0] * n[-1] * n[-2]). This is done in case we have negative numbers in the array and the product of two negative numbers yields a positive number which could be bigger than the product of the three highest numbers.
The max function is then used to return the maximum of the two potential results obtained above.
This way we are able to get the maximum product of three numbers in the given array nums.
Let's test this code with our examples:
Example 1: Input: nums = [1,2,3] Output: 6
Solution: We pass the input array into our function and get the maximum product of three numbers:
print(Solution().maximumProduct([1,2,3]))
output: 6
The output is as expected.
Example 2: Input: nums = [1,2,3,4] Output: 24
Solution: We pass the input array into our function and get the maximum product of three numbers:
print(Solution().maximumProduct([1,2,3,4]))
output: 24
The output is as expected.
Maximum Product Of Three Numbers Solution Code
1