1352. Product of the Last K Numbers - cocoder39/coco39_LC GitHub Wiki

1352. Product of the Last K Numbers

key takeaways: resetting products array when encountering 0

class ProductOfNumbers:

    def __init__(self):
        self.products = [-1]
        

    def add(self, num: int) -> None:
        if num == 0:
            self.products = [-1]
        else:
            product = self.products[-1] * num
            self.products.append(product)
        

    def getProduct(self, k: int) -> int:
        if k >= len(self.products): # k <= len - 1
            return 0
        
        return self.products[-1] // self.products[-k-1]