We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Greedy
- Mark and Toys
- Discussions
Mark and Toys
Mark and Toys
Sort by
recency
|
1049 Discussions
|
Please Login in order to post a comment
My current implementation uses the condition if (k - item > 0) This condition prevents purchasing an item when the remaining budget becomes exactly zero after the purchase. However, according to the problem statement, the goal is to maximize the number of toys that can be purchased without exceeding the budget. There is no restriction that the remaining budget must stay positive. Reaching exactly zero should be considered valid, since: The total cost does not exceed the budget. if (k - item > 0) means the algorithm only allows purchases when some money remains after buying the toy This incorrectly excludes valid scenarios where: k - item == 0 for example : prices = [1, 2, 3, 4] k = 6 The algorithm stops early and returns 2 instead of 3 This is not a valid logical restriction according to the problem definition. The condition should be updated to: if (k - item >= 0) The test cases should also ensure that scenarios where the budget becomes exactly zero are included, since these are valid and expected outcomes. public static int maximumToys(List prices, int k) { List SortedPrices = prices.OrderBy(x=>x).ToList(); int cnt = 0; foreach(var item in SortedPrices) { if(k-item>0) { cnt++; k-=item; } else { break; } } return cnt; }
}
The budget is fully utilized.
No constraint in the problem forbids spending the entire amount.
It seems thisproblem is not about sorting and it's more about having greedy thinking! So using a built-in sort apparently is acceptable!
Simple Java Solution:
JS