Maximum Product of Three Numbers LeetCode solution in Python

1
class Solution:
2
def maximumProduct(self, nums: List[int]) -> int:
3
# TC = O(NlogN) because sorting the array
4
# SC = O(1); no extra space needed; sorting was done in place.
5

6
# sorting the array in descending order
7
nums.sort(reverse=True)
8

9
# maximum product can only occur for:
10
# 1. positive no * positive no * positive no
11
# 2. negative no * negative no * positive no
12

13
# one negative and two positives and all negatives wont give max product
14
# case where all numbers in the array are negative
15
# eg : [-4,-3,-2,-1] is covered in all positives
16

17
return max(nums[0] * nums[1] * nums[2], nums[-1] * nums[-2] * nums[0])

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0