Created
August 20, 2017 07:23
-
-
Save farkwun/2da163d448004373c059096b0a788db3 to your computer and use it in GitHub Desktop.
628. Maximum Product of Three Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://leetcode.com/problems/maximum-product-of-three-numbers/description/ | |
class Solution(object): | |
def maximumProduct(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: int | |
""" | |
length = len(nums) | |
if length == 3: | |
return nums[0] * nums[1] * nums[2] | |
nums.sort() | |
head = 0 | |
tail = len(nums) - 1 | |
nums_found = 0 | |
while nums_found < 3: | |
if (nums[head] * nums[head+1]) > (nums[tail-1] * nums[tail]) and nums_found <= 1 : | |
head += 2 | |
else: | |
tail -= 1 | |
nums_found = head + (length - 1 - tail) | |
ans = 1 | |
for x in nums[:head]: | |
ans *= x | |
for x in nums[tail + 1:]: | |
ans *= x | |
return ans | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment