aboutsummaryrefslogtreecommitdiff
path: root/product_last_k_num.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-02-13 20:18:20 -0700
committerJack Sangdahl <[email protected]>2025-02-13 20:18:20 -0700
commit174c3b55b04c6a71e22712ce599afdece018ee39 (patch)
treecfeef243ad79c7b6288c4080602a5961962c6e78 /product_last_k_num.py
parentc925f1740cfe00cea69b6e091dcb38d114887ad3 (diff)
downloadleetcode-174c3b55b04c6a71e22712ce599afdece018ee39.tar.gz
leetcode-174c3b55b04c6a71e22712ce599afdece018ee39.zip
1352. product of the last k numbers
Diffstat (limited to 'product_last_k_num.py')
-rw-r--r--product_last_k_num.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/product_last_k_num.py b/product_last_k_num.py
new file mode 100644
index 0000000..e555476
--- /dev/null
+++ b/product_last_k_num.py
@@ -0,0 +1,47 @@
+# 1352. Product of the Last K Numbers
+
+"""
+design an algorithm that accepts a stream of integers and retrieves the
+product of the last 'k' integers of the stream. implement the
+'ProductOfNumbers' class. the test cases are generated so that at any time,
+the product of any contiguous sequence of numbers will fit into a single
+32-bit integer without overflowing.
+"""
+
+
+class ProductOfNumbers(object):
+ def __init__(self):
+ self.pre = [1]
+
+ def add(self, num):
+ """
+ :type num: int
+ :rtype: None
+ """
+ if num == 0:
+ self.pre = [1]
+ else:
+ self.pre.append(self.pre[-1] * num)
+
+ def getProduct(self, k):
+ """
+ :type k: int
+ :rtype: int
+ """
+ if k >= len(self.pre):
+ return 0
+ return self.pre[-1] / self.pre[-k - 1]
+
+
+if __name__ == "__main__":
+ obj = ProductOfNumbers()
+ obj.add(3)
+ obj.add(0)
+ obj.add(2)
+ obj.add(5)
+ obj.add(4)
+ print(obj.getProduct(2))
+ print(obj.getProduct(3))
+ print(obj.getProduct(4))
+ obj.add(8)
+ print(obj.getProduct(2))