Similar Problems
Similar Problems not available
Shopping Offers - Leetcode Solution
Companies:
LeetCode: Shopping Offers Leetcode Solution
Difficulty: Medium
Topics: backtracking bit-manipulation array dynamic-programming
Problem statement:
Given a list of prices and a list of discount percentages, implement the Cashier class to get the final price of all products for a customer. The Cashier class takes in three parameters, n, discount, and products.
n: an integer representing the number of products. discount: an integer representing the discount percentage. products: a list where the ith element represents the price of the ith product
The Cashier class has one method:
getBill(product, amount): Calculate the final price after applying the discount. The method takes in two parameters, product and amount product: a list representing the product id's in the current order. amount: a list representing the quantity of each product id in the current order.
The problem is to calculate the final price after applying the discount.
Solution:
We can define a constructor of the 'Cashier' class that would take three parameters n, discount, and products. The constructor would initialize the variables that would be used later in this class.
class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.n = n
self.discount = discount / 100
self.prices = {}
for i in range(n):
self.prices[products[i]] = prices[i]
self.count = 0
Here, we have stored the prices of all the products in a dictionary 'self.prices' with the product id as the key and the price as the value.
Next, we can write a method 'getBill' that would calculate the final price after applying the discount:
def getBill(self, product: List[int], amount: List[int]) -> float:
self.count += 1
total = 0
for i in range(len(product)):
total += self.prices[product[i]] * amount[i]
if self.count % self.n == 0:
total = total - (self.discount * total)
return total
Here, we have calculated the total price for all the products in the order by multiplying the price of each product with its quantity and adding the results. Next, we have checked if the total number of customers is divisible by n, which represents the frequency of applying the discount. If yes, we apply the discount and return the final price after discount. Otherwise, we return the total price without any discount.
This solution would work fine for the given problem and would result in O(n) time complexity.
Shopping Offers Solution Code
1