Skip to content

1357. Apply Discount Every n Orders 👎

  • Time:
    • Constructor: $O(|\texttt{products}|)$
    • getBill(product: list[int], amount: list[int]): $O(|\texttt{product})$
  • Space: $O(|\texttt{products}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Cashier {
 public:
  Cashier(int n, int discount, vector<int>& products, vector<int>& prices)
      : n(n), discount(discount) {
    for (int i = 0; i < products.size(); ++i)
      productToPrice[products[i]] = prices[i];
  }

  double getBill(vector<int> product, vector<int> amount) {
    ++count;
    int total = 0;
    for (int i = 0; i < product.size(); ++i)
      total += productToPrice[product[i]] * amount[i];
    return count % n == 0 ? total * (1 - discount / 100.0) : total;
  }

 private:
  const int n;
  const int discount;
  unordered_map<int, int> productToPrice;
  int count = 0;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Cashier {
  public Cashier(int n, int discount, int[] products, int[] prices) {
    this.n = n;
    this.discount = discount;
    for (int i = 0; i < products.length; ++i)
      productToPrice.put(products[i], prices[i]);
  }

  public double getBill(int[] product, int[] amount) {
    ++count;
    int total = 0;
    for (int i = 0; i < product.length; ++i)
      total += productToPrice.get(product[i]) * amount[i];
    return count % n == 0 ? total * (1 - discount / 100.0) : total;
  }

  private int n;
  private int discount;
  private Map<Integer, Integer> productToPrice = new HashMap<>();
  private int count = 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Cashier:
  def __init__(
      self,
      n: int,
      discount: int,
      products: list[int],
      prices: list[int],
  ):
    self.n = n
    self.discount = discount
    self.productToPrice = dict(zip(products, prices))
    self.count = 0

  def getBill(self, product: list[int], amount: list[int]) -> float:
    self.count += 1
    total = sum(self.productToPrice[p] * amount[i]
                for i, p in enumerate(product))
    if self.count % self.n == 0:
      return total * (1 - self.discount / 100)
    return total