LeetCode: Maximum Product of Three Numbers
Question
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: [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Solution
def maximum_product(nums)
# two possilbe scenaros for maximum product: could be all positive
# 1. 3 maximum numbers are all positive
# 2. 2 negative number(smallest) * 1 positive number(largest)
# take 2 smallest numbers
min_nums = nums.min(2)
# take 3 largest numbers
max_nums = nums.max(3)
# result is to compare which scenaro has maximum product
[max_nums[0] * max_nums[1] * max_nums[2], max_nums[0] * min_nums[0] * min_nums[1]].max
end
Comments