Skip to content

Instantly share code, notes, and snippets.

@farkwun
Created August 20, 2017 07:23
Show Gist options
  • Save farkwun/2da163d448004373c059096b0a788db3 to your computer and use it in GitHub Desktop.
Save farkwun/2da163d448004373c059096b0a788db3 to your computer and use it in GitHub Desktop.
628. Maximum Product of Three Numbers
# 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