Find Optimal Discount from Multiple Promotion Types
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests ability to compare multiple discount strategies with different application rules and select the best outcome while handling edge cases like empty inputs and clamping.
You are building a pricing engine for an e-commerce platform that needs to determine the final checkout amount after applying the most beneficial discount.
You receive three inputs:
- A list of item prices (each a non-negative number)
- A shipping fee (a non-negative number)
- A list of available discounts
There are two types of discounts:
- Percentage discounts: Apply only to the merchandise subtotal (sum of item prices), not to shipping. Represented with
"type": "percentage"and a"value"between 0 and 100. - Fixed-amount discounts: Subtract a dollar amount from the combined merchandise and shipping total. Represented with any other type (typically
"type": "fixed") and a non-negative"value".
Discount Application Rules:
- You may apply at most one discount to an order
- Applying no discount is always a valid option
- For a percentage discount with value
p: the merchandise subtotal is multiplied by(1 - p/100), then shipping is added at full price - For a fixed discount with value
d: subtractdfrom the sum of merchandise and shipping - The final amount can never be negative; if any calculation yields a negative result, return 0 instead
Your Task:
Write a function that computes which discount (if any) produces the lowest final amount, and return both that minimum amount and an identifier for the chosen discount.
Return a dictionary with two keys:
"total": the minimum achievable payment amount"promotion_index": the zero-based index of the selected discount in the input list, orNoneif no discount was applied
When multiple options produce the same final amount, prefer the earlier option (lower index), or None if the no-discount option ties for best.
Constraints:
- 0 ≤ number of items ≤ 1000
- 0 ≤ each item price ≤ 10000
- 0 ≤ shipping fee ≤ 1000
- 0 ≤ number of discounts ≤ 100
- For percentage discounts: 0 ≤ value ≤ 100
- For fixed discounts: 0 ≤ value ≤ 100000
- All prices and fees are floating-point numbers
Examples
Example 1
Input: find_best_discount([20, 30], 5, [{'type': 'percentage', 'value': 10}, {'type': 'fixed', 'value': 8}])
Output: {'total': 47, 'promotion_index': 1}
Example 2
Input: find_best_discount([], 5, [{'type': 'fixed', 'value': 10}])
Output: {'total': 0, 'promotion_index': 0}
Example 3
Input: find_best_discount([10], 2, [])
Output: {'total': 12, 'promotion_index': None}
Hints
Hint 1
Calculate the base total (items plus shipping) first, then treat it as one candidate alongside all discounts.
Hint 2
Remember that percentage discounts change only the item subtotal, while fixed discounts reduce the complete total including shipping.
Hint 3
Use strict inequality when comparing totals so that a discount must actually improve the price to be selected over the no-discount baseline.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that we can only use one discount at a time, so we need to evaluate each option independently and pick the best one.
Start by calculating the merchandise subtotal (sum of all item prices). The baseline scenario is applying no discount at all, which gives us subtotal + shipping_fee. This baseline is important because a discount that doesn't actually save money shouldn't be selected.
For each available discount:
- If it's a percentage type: reduce only the merchandise subtotal by the percentage, then add the full shipping fee
- If it's a fixed amount type: subtract the fixed amount from the complete total (merchandise plus shipping)
- Ensure the result never goes below zero by clamping
Track the minimum total seen so far and which discount produced it. Only update when a discount produces a strictly lower total than the current best. This ensures that if no discount helps, or if a discount merely ties the baseline, we return None as the promotion index.
The algorithm evaluates exactly n+1 scenarios (no discount plus each of the n available discounts) and selects the one yielding the lowest payment.
Why It Works
Every valid choice is evaluated: the no-discount baseline and each of the provided discounts. Since discount types have different application rules (percentage affects only items, fixed affects the full total), we must compute each one separately. By initializing with the baseline and using strict inequality for updates, we correctly handle edge cases like empty discount lists, ineffective discounts, and ties.
The clamping to zero ensures compliance with the rule that payment amounts cannot be negative, even when a large fixed discount exceeds the order total.
Complexity
- Time: O(m + n) where m is the number of items and n is the number of discounts. We sum the items once, then iterate through the discounts once.
- Space: O(1) extra space beyond the input, using only a few variables to track the best option.
Implementation
from typing import Dict, List, Optional
def find_best_discount(item_prices: List[float], shipping_fee: float, promotions: List[Dict[str, float]]) -> Dict[str, Optional[float]]:
items_sum = sum(item_prices)
best_total = items_sum + shipping_fee
best_promotion = None
for index, promotion in enumerate(promotions):
if promotion["type"] == "percentage":
total = items_sum * (1 - promotion["value"] / 100) + shipping_fee
else:
total = max(0.0, items_sum + shipping_fee - promotion["value"])
total = max(0.0, total)
if total < best_total:
best_total = total
best_promotion = index
return {"total": best_total, "promotion_index": best_promotion}