|
| 1 | +/** |
| 2 | + * 1357. Apply Discount Every n Orders |
| 3 | + * https://leetcode.com/problems/apply-discount-every-n-orders/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a supermarket that is frequented by many customers. The products sold at the supermarket |
| 7 | + * are represented as two parallel integer arrays products and prices, where the ith product has an |
| 8 | + * ID of products[i] and a price of prices[i]. |
| 9 | + * |
| 10 | + * When a customer is paying, their bill is represented as two parallel integer arrays product and |
| 11 | + * amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much |
| 12 | + * of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price |
| 13 | + * of the jth product). |
| 14 | + * |
| 15 | + * The supermarket decided to have a sale. Every nth customer paying for their groceries will be |
| 16 | + * given a percentage discount. The discount amount is given by discount, where they will be given |
| 17 | + * discount percent off their subtotal. More formally, if their subtotal is bill, then they would |
| 18 | + * actually pay bill * ((100 - discount) / 100). |
| 19 | + * |
| 20 | + * Implement the Cashier class: |
| 21 | + * - Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, |
| 22 | + * the discount, and the products and their prices. |
| 23 | + * - double getBill(int[] product, int[] amount) Returns the final total of the bill with the |
| 24 | + * discount applied (if any). Answers within 10-5 of the actual value will be accepted. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number} n |
| 29 | + * @param {number} discount |
| 30 | + * @param {number[]} products |
| 31 | + * @param {number[]} prices |
| 32 | + */ |
| 33 | +var Cashier = function(n, discount, products, prices) { |
| 34 | + this.customerCount = 0; |
| 35 | + this.discountPercent = discount; |
| 36 | + this.nthCustomer = n; |
| 37 | + this.priceMap = new Map(); |
| 38 | + for (let i = 0; i < products.length; i++) { |
| 39 | + this.priceMap.set(products[i], prices[i]); |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {number[]} product |
| 45 | + * @param {number[]} amount |
| 46 | + * @return {number} |
| 47 | + */ |
| 48 | +Cashier.prototype.getBill = function(product, amount) { |
| 49 | + this.customerCount++; |
| 50 | + let total = 0; |
| 51 | + for (let i = 0; i < product.length; i++) { |
| 52 | + total += this.priceMap.get(product[i]) * amount[i]; |
| 53 | + } |
| 54 | + if (this.customerCount % this.nthCustomer === 0) { |
| 55 | + return total * (100 - this.discountPercent) / 100; |
| 56 | + } |
| 57 | + return total; |
| 58 | +}; |
0 commit comments