Which statement best describes when to use a greedy algorithm instead of dynamic programming?
Think about whether making the best immediate choice guarantees the best overall solution.
Greedy algorithms work when choosing the best option at each step leads to the best overall solution. Dynamic programming is needed when decisions depend on previous choices and subproblems overlap.
What is the output of this Rust code that uses a greedy approach to make change?
fn greedy_coin_change(mut amount: i32, coins: &[i32]) -> Vec<i32> {
let mut result = Vec::new();
for &coin in coins {
let count = amount / coin;
amount %= coin;
result.push(count);
}
result
}
fn main() {
let coins = [25, 10, 5, 1];
let amount = 63;
let counts = greedy_coin_change(amount, &coins);
println!("{:?}", counts);
}Divide amount by each coin value starting from largest coin.
The code divides 63 by 25 to get 2 coins, remainder 13. Then 13 by 10 is 1 coin, remainder 3. Then 3 by 5 is 0 coins, remainder 3. Finally 3 by 1 is 3 coins.
What is the output of this Rust code that uses dynamic programming to compute Fibonacci numbers?
fn fib_dp(n: usize) -> usize {
let mut dp = vec![0; n + 1];
dp[0] = 0;
if n > 0 {
dp[1] = 1;
}
for i in 2..=n {
dp[i] = dp[i - 1] + dp[i - 2];
}
dp[n]
}
fn main() {
println!("{}", fib_dp(7));
}Recall Fibonacci sequence: 0,1,1,2,3,5,8,13,...
fib_dp(7) returns the 7th Fibonacci number (0-based index), which is 13.
Consider this Rust code for coin change using a greedy approach. Why does it fail for amount = 30 with coins [25, 10, 6, 1]?
fn greedy_coin_change(mut amount: i32, coins: &[i32]) -> Vec{ let mut result = Vec::new(); for &coin in coins { let count = amount / coin; amount %= coin; result.push(count); } result } fn main() { let coins = [25, 10, 6, 1]; let amount = 30; let counts = greedy_coin_change(amount, &coins); println!("{:?}", counts); }
Try to find the minimum coins needed for 30 with given coins.
The greedy approach picks 25 once, then 5 coins of 1, totaling 6 coins. But the optimal solution is 3 coins of 10, totaling 3 coins. Greedy fails because local best choice (25) is not part of global best solution.
You have a list of jobs with start time, end time, and profit. You want to select jobs that don't overlap and maximize total profit. Which approach is best?
Think about overlapping intervals and how to combine solutions.
Weighted interval scheduling requires checking previous compatible jobs to maximize profit, which dynamic programming handles efficiently. Greedy by profit alone can fail due to overlaps.
