Maximum Product of Three Numbers

Problem Id: 628 Difficulty: Easy


Intuition

Solution


class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        pos = [num for num in nums if num > 0]
        neg = [num for num in nums if num < 0]
        ans = nums[0] * nums[1] * nums[2]
        if 0 in nums:
            ans = max(ans, 0)
        m = []
        for _ in range(3):
            if not pos:
                break
            m.append(max(pos))
            pos.remove(m[-1])
        mm = []
        for _ in range(2):
            if not neg:
                break
            mm.append(min(neg))
            neg.remove(mm[-1])

        if len(m) > 2:
            ans = max(ans, m[0] * m[1] * m[2])
        if m and len(mm) > 1:
            ans = max(ans, m[0] * mm[0] * mm[1])
        return ans