---
# System prepended metadata

title: 1352. Product of the Last K Numbers
tags: [Leetcode, Design, Medium]

---

# 1352. Product of the Last K Numbers
###### tags: `Leetcode` `Medium` `Design`
Link: https://leetcode.com/problems/product-of-the-last-k-numbers/description/
## 思路
直觉的想法就是构造前缀乘积的数组，令pre[i]表示从nums[1]连续乘到nums[i]的积。假设当前已经有n个元素，那么最后k个元素的乘积就是pre[n]/pre[n-k]
但是由于有可能插入的数字等于0，这样的话就会导致后面的所有前缀乘积都是0，还有可能面对除数=0的情况，解决的办法就是我们记录最后面出现的0 并且如果出现0我们就重新计算乘积
如果后k个数里面包含最后出现的0 直接return 0
如果不包含再计算乘积
## Code
```java=
class ProductOfNumbers {
    List<Integer> prefix;
    int lastZero = 0;
    public ProductOfNumbers() {
        prefix = new ArrayList<>();
        prefix.add(1);
    }
    
    public void add(int num) {
        if(num==0){
            lastZero = prefix.size();
            prefix.add(1);
        }
        else{
            int prev = prefix.get(prefix.size()-1);
            prefix.add(num*prev);
        }
    }
    
    public int getProduct(int k) {
        if(prefix.size()-k-1<lastZero) return 0;
        return prefix.get(prefix.size()-1)/prefix.get(prefix.size()-k-1);
    }
}
```