난이도: Medium
문제 설명
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:
ProductOfNumbers()
Initializes the object with an empty stream.void add(int num)
Appends the integernum
to the stream.int getProduct(int k)
Returns the product of the lastk
numbers in the current list. You can assume that always the current list has at leastk
numbers.
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.
문제 예제
Example:
Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
Output
[null,null,null,null,null,null,20,40,0,null,32]
Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // [3]
productOfNumbers.add(0); // [3,0]
productOfNumbers.add(2); // [3,0,2]
productOfNumbers.add(5); // [3,0,2,5]
productOfNumbers.add(4); // [3,0,2,5,4]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8); // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32
제한 사항
0 <= num <= 100
1 <= k <= 4 * 104
- At most
4 * 104
calls will be made toadd
andgetProduct
. - The product of the stream at any point in time will fit in a 32-bit integer.
Follow-up: Can you implement both GetProduct
and Add
to work in O(1)
time complexity instead of O(k)
time complexity?
✏️ Solution(솔루션)
class ProductOfNumbers:
def __init__(self):
self.prefix = []
self.n = 0
def add(self, num: int) -> None:
if not self.prefix and num != 0:
self.prefix.append(num)
elif num == 0:
self.prefix = []
self.n = -1
else:
self.prefix.append(self.prefix[-1] * num)
self.n+=1
def getProduct(self, k: int) -> int:
#print(self.prefix, k, self.n)
if self.n > k:
return self.prefix[-1] // self.prefix[self.n - k - 1]
elif self.n == k:
return self.prefix[-1]
else:
return 0
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
누적합 문제 풀듯이 풀면 될 것 같았다.
만약 1, 2, 3, 4, 5 순서대로 add 해준다면 다음과 같이 저장할 수 있다. --> [1, 2, 6, 24, 120]
만약 여기서 k가 2로 getProduct를 한다면
prefix[-1] // prefix[5-2-1] 값을 return하면 된다.
답은 4*5 = 20이 될텐데, prefix[-1] = 120이다. 또 prefix[2] = 6이기 때문에 120//6 = 20으로 원하는 결과를 반환할 수 있다.
하지만 변수가 있었다. 한번 0이 들어오면 prefix에 저장되는 값이 계속 0이 된다는 것이었다.
따라서 0이 들어오면 prefix를 빈 리스트로 바꿔주었다.
이렇게 하면 현재 prefix의 길이와 k의 값을 비교해서 k가 더 크다면 무조건 0을 return할 수 있기 때문이다.
이제, 만약 k와 prefix 길이가 같다면 단순히 prefix[-1]을 return하면 되고 prefix의 길이가 더 크다면 앞서 설명했듯이 prefix[-1]//prefix[n-k-1] 값을 return 하면 된다.
0을 어떻게 처리해야할까 생각하다가 시간을 많이 보낸 것 같다...
문제: 1352. Product of the Last K Numbers
깃허브: github
algorithmPractice/LeetCode/1477-product-of-the-last-k-numbers at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 3066. Minimum Operations to Exceed Threshold Value II (Python) (0) | 2025.02.13 |
---|---|
[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits (Python) (0) | 2025.02.12 |
[LeetCode] 1910. Remove All Occurrences of a Substring (Python) (0) | 2025.02.11 |
[LeetCode] 3174. Clear Digits (Python) (0) | 2025.02.10 |
[LeetCode] 2364. Count Number of Bad Pairs (Python) (0) | 2025.02.09 |