Skip to main content

1352.js

/** ------------------------------------------------------------------------------
*
* 1352. Product of the Last K Numbers
* Topics: Prefix Sum
* https://leetcode.com/problems/product-of-the-last-k-numbers/?envType=daily-question&envId=2025-02-14
*
------------------------------------------------------------------------------ */
var ProductOfNumbers = function () {
this.prefix = [1]
}

/**
* @param {number} num
* @return {void}
*/
ProductOfNumbers.prototype.add = function (num) {
if (num === 0) {
this.prefix = [1]
} else {
this.prefix.push(this.prefix[this.prefix.length - 1] * num)
}
}

/**
* @param {number} k
* @return {number}
*/
ProductOfNumbers.prototype.getProduct = function (k) {
const len = this.prefix.length
if (k >= len) {
return 0
}
return this.prefix[len - 1] / this.prefix[len - 1 - k]
}

/**
* Your ProductOfNumbers object will be instantiated and called as such:
* var obj = new ProductOfNumbers()
* obj.add(num)
* var param_2 = obj.getProduct(k)
*/