Python, Straightforward with Explanation

  • 4

    Sort the array. Any "middle" numbers not in the first 3 or last 3 cannot be used in the final answer. If we are using a middle number, it must have both a left-neighbor and a right-neighbor, and switching to one of these neighbors will increase the product.

    def maximumProduct(self, A):
        if len(A) > 6:
            A = A[:3] + A[-3:]
        return max(A[i] * A[j] * A[k]
        	       for i in xrange(len(A))
        	       for j in xrange(i+1, len(A))
        	       for k in xrange(j+1, len(A)))

  • 0

    Just a little variation.

    def maximumProduct(self, A):
        del A[3:-3]
        return max(a * b * c for a, b, c in itertools.combinations(A, 3))

  • 0
    import functools
    import itertools
    from operator import mul
    class Solution:
        def maximumProduct(self, nums):
            :type nums: List[int]
            :rtype: int
            nums = sorted(nums)
            del nums[3:-3]
            return max(functools.reduce(mul, c) for c in itertools.combinations(nums, 3))

  • 0

    @zizhengwu said in Python, Straightforward with Explanation:

    more rigorous

    How so?

  • 0

    @zizhengwu why more rigorous?

Log in to reply

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