Leetcode 2288: Apply Discount to Prices

grid47
grid47
Exploring patterns and algorithms
Mar 23, 2024 8 min read

You are given a sentence, which contains words that may include prices represented by a dollar sign (’$’) followed by a sequence of digits. For each word in the sentence that represents a price, apply a given discount percentage and update the word. The price should be updated with exactly two decimal places. The goal is to return a modified sentence where the updated prices reflect the discount.
Problem
Approach
Steps
Complexity
Input: You are given a string sentence where words are separated by single spaces. Each word may represent a price in the form of a dollar sign followed by digits. An integer discount is also provided, which is the percentage of discount to be applied to the prices.
Example: Input: sentence = "apple $100 orange $200 banana", discount = 20
Constraints:
• 1 <= sentence.length <= 105
• sentence consists of lowercase English letters, digits, '$', and spaces.
• All words in the sentence are separated by a single space.
• Prices will be positive numbers without leading zeros.
• 0 <= discount <= 100
Output: Return the modified sentence where each price word has been updated with the discount applied. The updated price should have exactly two decimal places.
Example: Output: "apple $80.00 orange $160.00 banana"
Constraints:
Goal: The goal is to apply a discount to each word representing a price and update the price accordingly. The price should be formatted with two decimal places.
Steps:
• Step 1: Split the sentence into words.
• Step 2: For each word, check if it represents a price (starts with '$' followed by digits).
• Step 3: If the word is a price, calculate the new price after applying the discount.
• Step 4: Format the discounted price to two decimal places and update the word in the sentence.
• Step 5: Join the words back together to form the modified sentence and return it.
Goal: Each price word consists of a dollar sign followed by up to 10 digits. The discount is an integer between 0 and 100.
Steps:
Assumptions:
• All words representing prices are valid, meaning they are correctly formatted with a dollar sign followed by digits.
• The discount will always be between 0 and 100, inclusive.
Input: Input: sentence = "apple $100 orange $200 banana", discount = 20
Explanation: Here, '$100' will be discounted by 20%, resulting in '$80.00'. '$200' will be discounted by 20%, resulting in '$160.00'. The final sentence will be: 'apple $80.00 orange $160.00 banana'.

Input: Input: sentence = "item $50 item2 $30", discount = 10
Explanation: In this case, '$50' will be discounted by 10%, resulting in '$45.00'. '$30' will be discounted by 10%, resulting in '$27.00'. The final sentence will be: 'item $45.00 item2 $27.00'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus