Traveling Shopper - FreeCodeCamp #134 Daily Challenge
2 min
π Problem Summary
Given an initial amount and a list of items to buy (both in the format ["Amount", "Currency"]), how many can you buy in order, using the following conversion table?
| Currency | Equivalent in USD |
|---|---|
| USD | 1.00 USD |
| EUR | 1.10 USD |
| GBP | 1.25 USD |
| JPY | 0.0070 USD |
| CAD | 0.75 USD |
- If you can buy all, return βBuy them all!β
- Otherwise, return βBuy the first x itemsβ (x = number of items you can buy in order).
π Analysis & Strategy
The key is to convert everything to USD before comparing. This avoids errors and simplifies the calculation. The process is:
- Convert the initial amount to USD.
- Iterate through the item list, converting each price to USD.
- Simulate sequential purchases: if you can afford it, subtract; if not, stop and return how many you could buy.
Why not convert to the original currency? Because all rates are given relative to USD, and converting everything to a single currency is more direct and less error-prone.
π§ͺ Key Test Cases
- The amount is enough for some but not all items β should return the maximum possible.
- The amount is exactly enough for all β βBuy them all!β
- Amount and items in mixed currencies β must convert correctly.
- Less common currencies (JPY, CAD) β robustness.
- Not enough for even the first item β βBuy the first 0 items.β
- Money left after buying everything β still, βBuy them all!β
π‘ Commented Implementation
const rates = {
USD: 1.0,
EUR: 1.1,
GBP: 1.25,
JPY: 0.007,
CAD: 0.75,
}
export default function buyItems(amount, items) {
// Convert initial amount to USD
let budget = Number.parseFloat(amount[0]) * rates[amount[1]]
let count = 0
for (const [price, currency] of items) {
const priceUSD = Number.parseFloat(price) * rates[currency]
if (budget >= priceUSD) {
budget -= priceUSD
count++
}
else {
return `Buy the first ${count} items.`
}
}
return 'Buy them all!'
}β±οΈ Complexity
- Time: (single pass through the list)
- Space: (no structures proportional to input)
β οΈ Edge Cases & Tips
- Not enough for even the first item β βBuy the first 0 items.β
- Exactly enough or money left over β βBuy them all!β
- Always convert to USD before comparing.
- Use
parseFloatto handle decimals and integers.
π€ Reflections & Learnings
- Array destructuring.
- Currency conversion with a fixed table.
- Sequential greedy simulation.
- Simple, clear, and optimal code for this case.