Complete the code to select the next activity with the earliest finish time.
int selectNextActivity(List<Activity> activities) {
int n = activities.size();
int lastFinish = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (activities.get(i).start >= [1]) {
count++;
lastFinish = activities.get(i).finish;
}
}
return count;
}The greedy choice is to pick the next activity that starts after the last selected activity finishes. So we compare the current activity's start time with lastFinish.
Complete the code to sort activities by their finish time before selecting them.
Collections.sort(activities, (a, b) -> a.[1] - b.[1]);
Sorting activities by their finish time allows the greedy algorithm to pick the earliest finishing activity first, which leads to an optimal solution.
Fix the error in the greedy coin change algorithm that fails for certain coin sets.
int minCoins(int[] coins, int amount) {
int count = 0;
for (int i = coins.length - 1; i >= 0; i--) {
while (amount >= [1]) {
amount -= coins[i];
count++;
}
}
return amount == 0 ? count : -1;
}The condition should check if the remaining amount is at least the value of the current coin coins[i] before subtracting it.
Fill both blanks to create a dictionary comprehension that filters words longer than 3 letters and maps them to their lengths.
Map<String, Integer> lengths = words.stream()
.filter(word -> word.length() [1] 3)
.collect(Collectors.toMap(word -> word, word -> word.[2]()));The filter keeps words with length greater than 3, and the map stores each word with its length using word.length().
Fill all three blanks to create a map comprehension that uppercases keys, keeps values, and filters values greater than 0.
Map<String, Integer> result = data.entrySet().stream()
.filter(e -> e.getValue() [1] 0)
.collect(Collectors.toMap(e -> e.getKey().[2](), e -> e.[3]()));The filter keeps entries with values greater than 0, so the operator should be '>' to exclude non-positive values. The keys are uppercased with toUpperCase(), and values are accessed with getValue().
