1352. Product of the Last K Numbers #1313
-
Topics: Design an algorithm that accepts a stream of integers and retrieves the product of the last Implement the
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Example 1:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to design a class that efficiently handles a stream of integers and can quickly return the product of the last ApproachThe key insight is to use prefix products to efficiently compute the product of the last
Let's implement this solution in PHP: 1352. Product of the Last K Numbers <?php
class ProductOfNumbers {
/**
* @var int[]
*/
private $prefixProducts;
/**
*/
function __construct() {
$this->prefixProducts = [1];
}
/**
* @param Integer $num
* @return NULL
*/
function add($num) {
if ($num == 0) {
$this->prefixProducts = [1];
} else {
$last = end($this->prefixProducts);
$this->prefixProducts[] = $last * $num;
}
}
/**
* @param Integer $k
* @return Integer
*/
function getProduct($k) {
$n = count($this->prefixProducts) - 1;
if ($k > $n) {
return 0;
}
return $this->prefixProducts[$n] / $this->prefixProducts[$n - $k];
}
}
// Example usage
$productOfNumbers = new ProductOfNumbers();
$productOfNumbers->add(3);
$productOfNumbers->add(0);
$productOfNumbers->add(2);
$productOfNumbers->add(5);
$productOfNumbers->add(4);
echo $productOfNumbers->getProduct(2) . "\n"; // Output: 20
echo $productOfNumbers->getProduct(3) . "\n"; // Output: 40
echo $productOfNumbers->getProduct(4) . "\n"; // Output: 0
$productOfNumbers->add(8);
echo $productOfNumbers->getProduct(2) . "\n"; // Output: 32
?> Explanation:
This approach ensures that both adding numbers and retrieving products are done in constant time, making the solution efficient even for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to design a class that efficiently handles a stream of integers and can quickly return the product of the last
k
integers. The challenge is to ensure that both the addition of numbers and the retrieval of the product are done efficiently, even with a large number of operations.Approach
The key insight is to use prefix products to efficiently compute the product of the last
k
elements. Here's the detailed approach:Prefix Products Array: Maintain an array where each element at index
i
represents the product of all numbers added after the last zero up to thei-th
element. This array starts with an initial value of1
to handle the base case.Handling Zeros: When a zero is added …