Skip to content

Commit 2721708

Browse files
committed
Product of the Last K Numbers
1 parent d18c7fb commit 2721708

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

1352-product-of-the-last-k-numbers.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/product-of-the-last-k-numbers/
3+
4+
Implement the class ProductOfNumbers that supports two methods:
5+
1. add(int num)
6+
Adds the number num to the back of the current list of numbers.
7+
2. getProduct(int k)
8+
9+
Returns the product of the last k numbers in the current list.
10+
You can assume that always the current list has at least k numbers.
11+
At any time, the product of any contiguous sequence of numbers will fit
12+
into a single 32-bit integer without overflowing.
13+
14+
Example:
15+
16+
Input
17+
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct",
18+
"add","getProduct"]
19+
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
20+
Output
21+
[null,null,null,null,null,null,20,40,0,null,32]
22+
23+
Explanation
24+
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
25+
productOfNumbers.add(3); // [3]
26+
productOfNumbers.add(0); // [3,0]
27+
productOfNumbers.add(2); // [3,0,2]
28+
productOfNumbers.add(5); // [3,0,2,5]
29+
productOfNumbers.add(4); // [3,0,2,5,4]
30+
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
31+
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
32+
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
33+
productOfNumbers.add(8); // [3,0,2,5,4,8]
34+
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32
35+
36+
Constraints:
37+
There will be at most 40000 operations considering both add and getProduct.
38+
0 <= num <= 100
39+
1 <= k <= 40000
40+
"""
41+
class ProductOfNumbers:
42+
43+
def __init__(self):
44+
self.product = [1]
45+
46+
def add(self, num: int) -> None:
47+
if num == 0:
48+
self.product = [1]
49+
else:
50+
self.product.append(self.product[-1]*num)
51+
52+
def getProduct(self, k: int) -> int:
53+
if k >= len(self.product):
54+
return 0
55+
return self.product[-1] // self.product[-k-1]
56+
57+
58+
# Your ProductOfNumbers object will be instantiated and called as such:
59+
# obj = ProductOfNumbers()
60+
# obj.add(num)
61+
# param_2 = obj.getProduct(k)

0 commit comments

Comments
 (0)