Similar Problems
Similar Problems not available
Apply Discount To Prices - Leetcode Solution
Companies:
LeetCode: Apply Discount To Prices Leetcode Solution
Difficulty: Medium
Topics: string
Problem Statement:
You are given an array of prices of items and a discount percentage. You need to apply the given discount percentage to all the prices and round the discounted price to the nearest integer. Return the final discounted prices after rounding them to the nearest integer.
Example:
Input: prices = [400, 200, 100], discount = 20 Output: [320, 160, 80] Explanation: Applying a 20% discount to all the prices, we get [320, 160, 80]. After rounding each value to the nearest integer, the final result is [320, 160, 80].
Solution:
The problem is very simple, we just need to apply the given discount percentage to all the prices and round the discounted price to the nearest integer. We can easily do this by iterating through the prices array and doing the following:
- Calculate the discounted price for each item by multiplying the price with the discount percentage and subtracting the result from the original price.
- Round the discounted price to the nearest integer using the built-in round() function in Python.
- Store the rounded discounted price in a new list.
- Return the new list with all the discounted prices rounded to the nearest integer.
Here is the Python code to implement the above logic:
def apply_discount_to_prices(prices, discount): discounted_prices = [] for price in prices: discounted_price = price * (100 - discount) / 100 discounted_price = round(discounted_price) discounted_prices.append(discounted_price) return discounted_prices
Test the function
prices = [400, 200, 100] discount = 20 print(apply_discount_to_prices(prices, discount)) # Output: [320, 160, 80]
Time Complexity:
The time complexity of the above solution is O(n) where n is the number of prices given in the input array. This is because we iterate through the whole prices array once to calculate the discounted price for each item.
Apply Discount To Prices Solution Code
1