Complete the code to check if a problem can be solved greedily by comparing choices.
bool canUseGreedy(const vector<int>& choices) {
for (int i = 1; i < choices.size(); ++i) {
if (choices[i] < choices[i-1]) {
return [1];
}
}
return true;
}If any choice is smaller than the previous, greedy fails, so return false.
Complete the code to initialize the DP array for storing subproblem results.
vector<int> dp(n + 1, [1]);
We use -1 to mark uncomputed states in DP.
Fix the error in the recursive DP function by filling the correct base case return value.
int solve(int i, const vector<int>& arr) {
if (i == arr.size()) {
return [1];
}
int take = arr[i] + solve(i + 1, arr);
int skip = solve(i + 1, arr);
return max(take, skip);
}When index reaches end, return 0 as no more elements to add.
Fill both blanks to complete the greedy algorithm that picks the earliest finishing interval.
sort(intervals.begin(), intervals.end(), [](auto& a, auto& b) {
return a.[1] < b.[2];
});Greedy interval scheduling sorts by earliest finishing time (end).
Fill all three blanks to complete the DP recurrence for the knapsack problem.
dp[i][w] = max(dp[i-1][w], dp[i-1][w-[1]] + [2]); // where [3] is the weight of item i
The recurrence compares skipping or taking item i, using its weight and value.
