Problem statement

https://binarysearch.com/problems/Max-Product-of-Two-Numbers/

Solution

We can sort number and then choose between product of smallest two and biggest two. Almost the same as Leetcode 1464. Maximum Product of Two Elements in an Array.

Complexity

It is O(n log n) for time and O(n) for space. Notice that time can be made O(n) in fact.

Code

class Solution:
    def solve(self, nums):
        nums = sorted(nums)
        a1, a2 = nums[0], nums[1]
        b1, b2 = nums[-2], nums[-1]
        return max(a1 * a2, b1 * b2)