LeetCode 1357: Apply Discount Every n Orders Solution

Master LeetCode problem 1357 (Apply Discount Every n Orders), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1357. Apply Discount Every n Orders

Problem Explanation

Explanation:

To solve this problem, we can create a Cashier class with an initialization method Cashier(int n, int discount, int[] products, int[] prices) and a method double getBill(int[] product, int[] amount).

  1. In the Cashier constructor, we initialize the discount value, the count of customers before a discount is applied (n), and create a map to store the prices of products.
  2. In the getBill method, we calculate the subtotal of the customer's bill by iterating through the purchased products and their corresponding amounts.
  3. If the current customer is eligible for a discount (based on the count of customers), we apply the discount to the subtotal.
  4. Finally, we return the final total of the bill.

Java:

Solution Code

class Cashier {
    int n, discount, count;
    Map<Integer, Integer> productPrices;

    public Cashier(int n, int discount, int[] products, int[] prices) {
        this.n = n;
        this.discount = discount;
        this.count = 0;
        productPrices = new HashMap<>();
        for (int i = 0; i < products.length; i++) {
            productPrices.put(products[i], prices[i]);
        }
    }

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1357 (Apply Discount Every n Orders)?

This page provides optimized solutions for LeetCode problem 1357 (Apply Discount Every n Orders) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1357 (Apply Discount Every n Orders)?

The time complexity for LeetCode 1357 (Apply Discount Every n Orders) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1357 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1357 in Java, C++, or Python.

Back to LeetCode Solutions