-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path1352-product-of-the-last-k-numbers.js
36 lines (33 loc) · 1.1 KB
/
1352-product-of-the-last-k-numbers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 1352. Product of the Last K Numbers
* https://leetcode.com/problems/product-of-the-last-k-numbers/
* Difficulty: 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 integer num to the stream.
* - int getProduct(int k) Returns the product of the last k numbers in the current list.
* You can assume that always the current list has at least k 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.
*/
var ProductOfNumbers = function() {
this.nums = [];
};
/**
* @param {number} num
* @return {void}
*/
ProductOfNumbers.prototype.add = function(num) {
this.nums.push(num);
};
/**
* @param {number} k
* @return {number}
*/
ProductOfNumbers.prototype.getProduct = function(k) {
return this.nums.slice(-k).reduce((product, n) => product * n, 1);
};