Python solution using heapq, beat 92%


  • 0
    S
    import heapq
    
    class Solution(object):
        def maximumProduct(self, nums):
            left = [] # 3 smallest
            right = []  # 3 largest
            for x in nums:
                if x < 0:
                    if len(left) < 3:
                        heapq.heappush(left,-x)
                    elif -x > left[0]:
                        heapq.heappush(left,-x)
                        heapq.heappop(left)
                else:
                    if len(right) < 3:
                        heapq.heappush(right,x)
                    elif x > right[0]:
                        heapq.heappush(right,x)
                        heapq.heappop(right)
            lr = [-x for x in left] + [x for x in right]
            lr.sort()
            return  max(lr[-3] * lr[-2] * lr[-1], lr[0] * lr[1] * lr[-1])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.