Product of the Last K Numbers in C++



Suppose we have the implement the class called ProductOfNumbers that supports two methods −

  • add(int num): This adds the number num to the back of the current list of numbers.

  • getProduct(int k): This returns the product of the last k numbers in the current list.

We can assume that always the current list has at least k numbers. So for example, if the input is like − add(3), add(0), add(2), add(5), add(4), getProduct(2), getProduct(3), getProduct(4), add(8), getProduct(2), then the output will be (after each function call) −

[3], [3, 0], [3, 0, 2], [3, 0, 2, 5], [3, 0, 2, 5, 4], then (5 * 4) = 20, then (2 * 5 * 4) = 40, then (0 * 2 * 5 * 4) = 0, then [3, 0, 2, 5, 4, 8], then (4 * 8) = 32.

To solve this, we will follow these steps −

  • In the initialization section, it will create an array, and put 1 into it

  • The add() method will take num

  • if num is 0, then clear the array, and insert 1, otherwise insert last_element * num into array

  • The getProduct() method will take k as input

  • n := size of the array

  • if k > n – 1, then return 0, otherwise dp[n - 1] / dp[n – k – 1]

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h> using namespace std; class ProductOfNumbers { public:    vector <int> dq;    ProductOfNumbers() {       dq.push_back(1);    }    void add(int num) {       if(num == 0){          dq.clear();          dq.push_back(1);       }       else{          dq.push_back(dq.back() * num);       }    }    int getProduct(int k) {       int n = (int)dq.size();       return k > n - 1? 0 : dq[n - 1] / dq[n - k - 1];    } }; main(){    ProductOfNumbers ob;    (ob.add(3));    (ob.add(0));    (ob.add(2));    (ob.add(5));    (ob.add(4));    cout << (ob.getProduct(2)) << endl;    cout << (ob.getProduct(3)) << endl;    cout << (ob.getProduct(4)) << endl;    (ob.add(8));    cout << (ob.getProduct(2)) << endl; }

Input

add(3) add(0) add(2) add(5) add(4) getProduct(2) getProduct(3) getProduct(4) add(8) getProduct(2)

Output

20 40 0 32
Updated on: 2020-04-29T12:42:02+05:30

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements