Leetcode 1477 Solution

This article provides solution to leetcode question 1477 (product-of-the-last-k-numbers)

https://leetcode.com/problems/product-of-the-last-k-numbers

Solution

class ProductOfNumbers:
def __init__(self): self.products = [1]
def add(self, num: int) -> None: if num == 0: self.products = [1] else: self.products.append(num * self.products[-1])
def getProduct(self, k: int) -> int: if k >= len(self.products): return 0 else: return self.products[-1] // self.products[-1 - k]
# Your ProductOfNumbers object will be instantiated and called as such: # obj = ProductOfNumbers() # obj.add(num) # param_2 = obj.getProduct(k)