Certainly! Here's the implementation of the maxProduct function:

import numpy as np

def maxProduct(nums):
    max_product = nums[0]
    min_product = nums[0]
    result = nums[0]
    
    for i in range(1, len(nums)):
        if nums[i] < 0:
            max_product, min_product = min_product, max_product
        
        max_product = max(nums[i], max_product * nums[i])
        min_product = min(nums[i], min_product * nums[i])
        
        result = max(result, max_product)
    
    return result

In this implementation, the function takes an integer array nums as input. It initializes three variables: max_product, min_product, and result. The max_product variable keeps track of the maximum product seen so far, min_product keeps track of the minimum product seen so far (to handle negative values), and result stores the final result.

The function loops through the array starting from the second element. For each element, it checks if the element is negative. If it is, it swaps the max_product and min_product variables, as a negative number can flip the sign of the product.

Then, it calculates the new maximum product by taking the maximum of the current element alone (nums[i]) or the product of the previous maximum product (max_product) and the current element (max_product * nums[i]). It also calculates the new minimum product similarly.

The result is updated by taking the maximum of the previous result and the new max_product.

Finally, the result is returned as the final product.

Now, let's run the provided test cases:

assert maxProduct(np.array([2, 3, -2, 4])) == 6
assert maxProduct(np.array([-2, 0, -1])) == 0

If the assertions pass without raising an AssertionError, it indicates that the implementation of the maxProduct function is correct.


原文地址: https://www.cveoy.top/t/topic/ZU2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录