LeetCode 2288: Apply Discount to Prices Solution

Master LeetCode problem 2288 (Apply Discount to Prices), 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.

2288. Apply Discount to Prices

Medium

Problem Explanation

Explanation:

  • We will iterate through the sentence word by word.
  • For each word that starts with '$', we will extract the price and apply the discount.
  • The discounted price will be formatted to have exactly two decimal places.
  • We will replace the original price in the sentence with the discounted price.
  • Finally, we will return the modified sentence.

Time Complexity: O(n), where n is the length of the sentence. Space Complexity: O(n), to store the modified sentence.

:

Solution Code

class Solution {
    public String applyDiscount(String sentence, int discount) {
        String[] words = sentence.split(" ");
        StringBuilder modified = new StringBuilder();

        for (String word : words) {
            if (word.startsWith("$")) {
                double price = Double.parseDouble(word.substring(1));
                double discountedPrice = price * (1 - (double)discount / 100);
                modified.append(String.format("$%.2f", discountedPrice)).append(" ");
            } else {
                modified.append(word).append(" ");
            }
        }

        return modified.toString().trim();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2288 (Apply Discount to Prices)?

This page provides optimized solutions for LeetCode problem 2288 (Apply Discount to Prices) 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 2288 (Apply Discount to Prices)?

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

Can I run code for LeetCode 2288 on DevExCode?

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

Back to LeetCode Solutions