Challenge - 5 Problems
Greedy Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Greedy Coin Change Algorithm
What is the output of the following C++ code that uses a greedy approach to make change with coin denominations 1, 5, and 10 for amount 18?
DSA C++
#include <iostream> #include <vector> using namespace std; int main() { vector<int> coins = {10, 5, 1}; int amount = 18; vector<int> result; for (int coin : coins) { while (amount >= coin) { amount -= coin; result.push_back(coin); } } for (int c : result) cout << c << " "; return 0; }
Attempts:
2 left
💡 Hint
Think about how the greedy algorithm picks the largest coin first until it cannot anymore.
✗ Incorrect
The greedy algorithm picks 10 first (amount becomes 8), then 5 (amount becomes 3), then three 1s to make the total 18.
🧠 Conceptual
intermediateWhy Greedy Fails for Some Coin Sets
Why does the greedy algorithm fail to find the minimum number of coins for the amount 6 when coin denominations are 1, 3, and 4?
Attempts:
2 left
💡 Hint
Consider how greedy picks coins and compare with the optimal solution.
✗ Incorrect
Greedy picks the largest coin (4), then two 1s, totaling 3 coins. The optimal is two 3s, totaling 2 coins.
🔧 Debug
advancedIdentify the Bug in Greedy Interval Scheduling
What error does the following C++ code produce when trying to select the maximum number of non-overlapping intervals using a greedy approach?
DSA C++
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<pair<int,int>> intervals = {{1,4}, {3,5}, {0,6}, {5,7}, {8,9}}; sort(intervals.begin(), intervals.end()); int count = 0; int end_time = 0; for (auto interval : intervals) { if (interval.first >= end_time) { count++; end_time = interval.second; } } cout << count << endl; return 0; }
Attempts:
2 left
💡 Hint
Check how intervals are sorted and what property greedy needs to work correctly.
✗ Incorrect
The code sorts intervals by start time, but greedy interval scheduling requires sorting by finish time to maximize intervals selected.
🚀 Application
advancedChoosing Tasks with Deadlines and Profits
Given tasks with deadlines and profits, which greedy strategy correctly maximizes total profit?
Attempts:
2 left
💡 Hint
Think about how to maximize profit while respecting deadlines.
✗ Incorrect
Sorting by profit descending and placing tasks as late as possible before their deadline ensures maximum profit without conflicts.
🧠 Conceptual
expertWhen Does Greedy Guarantee Optimality?
Which condition ensures that a greedy algorithm always produces an optimal solution?
Attempts:
2 left
💡 Hint
Recall the two main properties that justify greedy algorithms.
✗ Incorrect
Greedy algorithms work optimally when the problem has the greedy-choice property (local choices lead to global optimum) and optimal substructure (optimal solution contains optimal subsolutions).
