1352. Product of the Last K Numbers
1352. Product of the Last K Numbers
Description
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 integernumto the stream.int getProduct(int k)Returns the product of the lastknumbers in the current list. You can assume that always the current list has at leastknumbers.
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:
1 | Input |
Constraints:
0 <= num <= 1001 <= k <= 4 * 10^4- At most
4 * 10^4calls will be made toaddandgetProduct. - 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?
Hints/Notes
- 2025/03/21 Q2
- preSum
- Leetcode solution
Solution
Language: C++
1 | class ProductOfNumbers { |