Skip to content

Commit 8826f2a

Browse files
committed
Add solution #1352
1 parent 15c8ce1 commit 8826f2a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@
430430
1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium|
431431
1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy|
432432
1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy|
433+
1352|[Product of the Last K Numbers](./1352-product-of-the-last-k-numbers.js)|Medium|
433434
1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy|
434435
1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy|
435436
1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 1352. Product of the Last K Numbers
3+
* https://leetcode.com/problems/product-of-the-last-k-numbers/
4+
* Difficulty: Medium
5+
*
6+
* Design an algorithm that accepts a stream of integers and retrieves the product of the
7+
* last k integers of the stream.
8+
*
9+
* Implement the ProductOfNumbers class:
10+
* - ProductOfNumbers() Initializes the object with an empty stream.
11+
* - void add(int num) Appends the integer num to the stream.
12+
* - int getProduct(int k) Returns the product of the last k numbers in the current list.
13+
* You can assume that always the current list has at least k numbers.
14+
* - The test cases are generated so that, at any time, the product of any contiguous sequence
15+
* of numbers will fit into a single 32-bit integer without overflowing.
16+
*/
17+
18+
var ProductOfNumbers = function() {
19+
this.nums = [];
20+
};
21+
22+
/**
23+
* @param {number} num
24+
* @return {void}
25+
*/
26+
ProductOfNumbers.prototype.add = function(num) {
27+
this.nums.push(num);
28+
};
29+
30+
/**
31+
* @param {number} k
32+
* @return {number}
33+
*/
34+
ProductOfNumbers.prototype.getProduct = function(k) {
35+
return this.nums.slice(-k).reduce((product, n) => product * n, 1);
36+
};

0 commit comments

Comments
 (0)