Skip to main content
Back to problems
#1357
Medium Algorithms

Apply discount every n orders

Array Hash Table Design
65.4% acceptance
Feb 23, 2026
215
233
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i]. When a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product). The supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100). Implement the Cashier class: Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices. double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

pub struct Cashier {
  n: i32,
  discount: i32,
  price_map: HashMap<i32, i32>,
  count: i32,
}

impl Cashier {
  pub fn new(n: i32, discount: i32, products: Vec<i32>, prices: Vec<i32>) -> Self {
    let mut price_map = HashMap::new();
    for (p, pr) in products.into_iter().zip(prices.into_iter()) {
      price_map.insert(p, pr);
    }
    Cashier { n, discount, price_map, count: 0 }
  }

  pub fn get_bill(&mut self, product: Vec<i32>, amount: Vec<i32>) -> f64 {
    self.count += 1;
    let subtotal: f64 = product.iter().zip(amount.iter())
      .map(|(p, a)| self.price_map[p] as f64 * *a as f64)
      .sum();
    if self.count % self.n == 0 {
      subtotal * (100.0 - self.discount as f64) / 100.0
    } else {
      subtotal
    }
  }
}