Problem statement

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

Solution

Equal to Leetcode 0628 Maximum Product of Three Numbers.

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, nums):
        A = [float('-inf'), float('-inf'), float('-inf')]
        B = [float('inf'), float('inf')]
        for num in nums:
            if   num >= A[0]: A = [num, A[0], A[1]]
            elif num >= A[1]: A = [A[0], num, A[1]]
            elif num >= A[2]: A = [A[0], A[1], num]
                
            if   num <= B[0]: B = [num, B[0]]
            elif num <= B[1]: B = [B[0], num]

        return max(A[0]*A[1]*A[2], A[0]*B[0]*B[1])