Sunday, August 23, 2015

Leetcode 152. Maximum Product Subarray

https://leetcode.com/problems/maximum-product-subarray/

Note that a very small negative number can be very large after timing a negative number, so the min value should also be recorded.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        global_max, local_max, local_min = float("-inf"), 1, 1
        for x in A:
            local_max, local_min = max(x, local_max * x, local_min * x), min(x, local_max * x, local_min * x)
            global_max = max(global_max, local_max)
        return global_max
Run Time: 84 ms

No comments:

Post a Comment