-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
33 lines (30 loc) · 863 Bytes
/
solution.ts
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
class ProductOfNumbers {
sequence:number[];
zeroIndex = -1;
constructor () {
this.sequence = [1, ];
}
add (num: number): void {
if (num === 0) {
this.zeroIndex = this.sequence.length;
this.sequence.push(1);
} else {
const last = this.sequence[this.sequence.length - 1];
this.sequence.push(last * num);
}
}
getProduct (k: number): number {
const startIndex = this.sequence.length - 1 - k;
if (startIndex < this.zeroIndex) {
return 0;
}
const a = this.sequence[startIndex];
return this.sequence[this.sequence.length - 1] / a;
}
}
/**
* Your ProductOfNumbers object will be instantiated and called as such:
* var obj = new ProductOfNumbers()
* obj.add(num)
* var param_2 = obj.getProduct(k)
*/