Skip to content

Commit 260d6e6

Browse files
committed
Adding Efficient Solution for Problem - 628 - Maximum Product Three
1 parent 5be74b5 commit 260d6e6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 628
6+
## Problem Name: Maximum Product of Three Numbers
7+
##===================================
8+
#
9+
#Given an integer array, find three numbers whose product is maximum and output the maximum product.
10+
#
11+
#Example 1:
12+
#
13+
#Input: [1,2,3]
14+
#Output: 6
15+
#
16+
#Example 2:
17+
#
18+
#Input: [1,2,3,4]
19+
#Output: 24
20+
class Solution:
21+
def maximumProduct(self, nums):
22+
if len(nums) == 3: #Condition-check: If nums length is equal to three.
23+
return nums[0]*nums[1]*nums[2] #We return the muliplication of their value.
24+
else: #Condition-check: Otherwise
25+
nums.sort() #We sort the array.
26+
if nums[0] >= 0 or nums[-1] <= 0: #Condition-check: If sorted array has all positive numbers or negative numbers
27+
return nums[-1]*nums[-2]*nums[-3] #We multiply nums last three numbers to get max
28+
return max(nums[-1]*nums[-2]*nums[-3], nums[-1]*nums[0]*nums[1]) #Otherwise, we return max of given numbers

0 commit comments

Comments
 (0)