Python concise solution, O(N) and 1 line

  • 5

    My first solution using sort

    def maximumProduct(self, nums):
            return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])

    I found a exactly same solution in discuss. Anyway, O(NlogN) is not adorable and O(N) is possible.

    def maximumProduct(self, nums):
            a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
            return max(a[0] * a[1] * a[2], b[0] * b[1] * a[0])

    Make it 1 line if you like:

        def maximumProduct(self, nums):
            return max(nums) * max(a * b for a, b in [heapq.nsmallest(2, nums), heapq.nlargest(3, nums)[1:]])

  • 0

    @lee215 I guess It should be O(N) in the title, not O(1). If you mean O(1) memory, then specify it additionally.

  • 0
    This post is deleted!

Log in to reply

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