1357. Apply Discount Every n Orders
В супермаркете, который посещает множество покупателей, товары представлены двумя параллельными массивами целых чисел products и prices, где i-й товар имеет идентификатор products[i] и цену prices[i].
Когда покупатель оплачивает товар, его счет представлен двумя параллельными массивами целых чисел product и amount, где j-й приобретенный товар имеет идентификатор product[j], а amount[j] - количество купленного товара. Их промежуточный итог рассчитывается как сумма каждого amount[j] * (цена j-го товара).
Супермаркет решил провести распродажу. Каждому n-му покупателю, оплачивающему свои покупки, будет предоставлена скидка в процентах. Сумма скидки задается параметром discount, и покупатель получит скидку в discount процентов от своего промежуточного итога. Формально, если их промежуточный итог составляет bill, то они фактически заплатят bill * ((100 - discount) / 100).
Реализуйте класс Cashier:
Cashier(int n, int discount, int[] products, int[] prices): инициализирует объект с параметрами n, discount, а также массивами товаров и их цен.
double getBill(int[] product, int[] amount): возвращает итоговую сумму счета с примененной скидкой (если применима). Ответы, отличающиеся от фактического значения не более чем на 10^-5, будут приняты.
Пример
Input
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
Output
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
C# решение
сопоставлено/оригиналusing System;
using System.Collections.Generic;
public class Cashier {
private int n;
private int discount;
private Dictionary<int, int> productsPrices;
private int customerCount;
public Cashier(int n, int discount, int[] products, int[] prices) {
this.n = n;
this.discount = discount;
this.productsPrices = new Dictionary<int, int>();
for (int i = 0; i < products.Length; i++) {
this.productsPrices[products[i]] = prices[i];
}
this.customerCount = 0;
}
public double GetBill(int[] product, int[] amount) {
customerCount++;
double bill = 0.0;
for (int i = 0; i < product.Length; i++) {
bill += productsPrices[product[i]] * amount[i];
}
if (customerCount % n == 0) {
bill *= (100.0 - discount) / 100.0;
}
return bill;
}
}
C++ решение
auto-draft, проверить перед отправкой#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class Cashier {
private int n;
private int discount;
private unordered_map<int, int> productsPrices;
private int customerCount;
public Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {
this.n = n;
this.discount = discount;
this.productsPrices = new unordered_map<int, int>();
for (int i = 0; i < products.size(); i++) {
this.productsPrices[products[i]] = prices[i];
}
this.customerCount = 0;
}
public double GetBill(vector<int>& product, vector<int>& amount) {
customerCount++;
double bill = 0.0;
for (int i = 0; i < product.size(); i++) {
bill += productsPrices[product[i]] * amount[i];
}
if (customerCount % n == 0) {
bill *= (100.0 - discount) / 100.0;
}
return bill;
}
}
Java решение
auto-draft, проверить перед отправкойimport java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Cashier {
private int n;
private int discount;
private HashMap<int, int> productsPrices;
private int customerCount;
public Cashier(int n, int discount, int[] products, int[] prices) {
this.n = n;
this.discount = discount;
this.productsPrices = new HashMap<int, int>();
for (int i = 0; i < products.length; i++) {
this.productsPrices[products[i]] = prices[i];
}
this.customerCount = 0;
}
public double GetBill(int[] product, int[] amount) {
customerCount++;
double bill = 0.0;
for (int i = 0; i < product.length; i++) {
bill += productsPrices[product[i]] * amount[i];
}
if (customerCount % n == 0) {
bill *= (100.0 - discount) / 100.0;
}
return bill;
}
}
JavaScript решение
сопоставлено/оригиналclass Cashier {
constructor(n, discount, products, prices) {
this.n = n;
this.discount = discount;
this.productsPrices = new Map();
this.customerCount = 0;
for (let i = 0; i < products.length; i++) {
this.productsPrices.set(products[i], prices[i]);
}
}
getBill(product, amount) {
this.customerCount++;
let bill = 0.0;
for (let i = 0; i < product.length; i++) {
bill += this.productsPrices.get(product[i]) * amount[i];
}
if (this.customerCount % this.n === 0) {
bill *= (100 - this.discount) / 100.0;
}
return bill;
}
}
Python решение
сопоставлено/оригиналclass Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.n = n
self.discount = discount
self.productsPrices = dict(zip(products, prices))
self.customerCount = 0
def getBill(self, product: List[int], amount: List[int]) -> float:
self.customerCount += 1
bill = sum(self.productsPrices[prod] * amt for prod, amt in zip(product, amount))
if self.customerCount % self.n == 0:
bill *= (100 - self.discount) / 100.0
return bill
Go решение
сопоставлено/оригиналtype Cashier struct {
n int
discount int
productsPrices map[int]int
customerCount int
}
func Constructor(n int, discount int, products []int, prices []int) Cashier {
productsPrices := make(map[int]int)
for i := 0; i < len(products); i++ {
productsPrices[products[i]] = prices[i]
}
return Cashier{n, discount, productsPrices, 0}
}
func (this *Cashier) GetBill(product []int, amount []int) float64 {
this.customerCount++
bill := 0.0
for i := 0; i < len(product); i++ {
bill += float64(this.productsPrices[product[i]] * amount[i])
}
if this.customerCount % this.n == 0 {
bill *= float64(100 - this.discount) / 100.0
}
return bill
}
Algorithm
Инициализация объекта:
Создайте класс Cashier с конструктором, который принимает параметры n, discount, products и prices. В конструкторе инициализируйте необходимые переменные и создайте словарь для сопоставления идентификаторов продуктов с их ценами.
Обработка каждого счета:
Создайте метод getBill, который принимает массивы product и amount.
Вычислите промежуточный итог счета, умножая количество каждого продукта на его цену и суммируя результаты.
Увеличьте счетчик клиентов. Если клиент является n-м по счету, примените скидку к промежуточному итогу.
Верните итоговую сумму счета.
😎
Вакансии для этой задачи
Показаны активные вакансии с пересечением по тегам задачи.