[Java] preProduct | Simple and well explained
\n# Approach\n Describe your approach to solving the problem. \n1. Build a preproduct arraylist: arr[i] = arr[0] * arr[1] ... * arr[i] so we can easily use arr[
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Build a preproduct arraylist: arr[i] = arr[0] * arr[1]* ... * arr[i] so we can easily use arr[n] / arr[n - k] to calculate last k numbers\' product;\n2. Tricky part is whenever we got a 0, since the product from the end to any start point which is before this 0 will become 0.\n**How could we solve this issue?**\n**Just create a new ArrayList and start over!**\nWhich means now we have a brand new ArrayList, if k is larger than our new ArrayList size, which means it will include the 0 we met before, we can just return 0.\n\n# Code\n```\nclass ProductOfNumbers {\n    List<Integer> preProduct;\n    public ProductOfNumbers() {\n        preProduct = new ArrayList<>();\n    }\n    \n    public void add(int num) {\n        if(num == 0) {\n            preProduct = new ArrayList<>();\n        } else {\n            if(preProduct.size() == 0) preProduct.add(num);\n            else preProduct.add(preProduct.get(preProduct.size() - 1) * num);\n        }\n        \n    }\n    \n    public int getProduct(int k) {\n        if(preProduct.size() < k) return 0;\n        if(preProduct.size() == k) return preProduct.get(preProduct.size() - 1);\n        else return preProduct.get(preProduct.size() - 1) / preProduct.get(preProduct.size() - 1 - k);\n    }\n}\n\n/**\n * Your ProductOfNumbers object will be instantiated and called as such:\n * ProductOfNumbers obj = new ProductOfNumbers();\n * obj.add(num);\n * int param_2 = obj.getProduct(k);\n */\n```
['Java']