Complete the code to check if the problem has optimal substructure property.
bool HasOptimalSubstructure(int[] arr) {
// Optimal substructure means the problem can be broken into [1] subproblems
return arr.Length > 1;
}Optimal substructure means the problem can be divided into smaller independent subproblems whose solutions combine to solve the original problem.
Complete the code to identify if subproblems overlap for DP application.
bool HasOverlappingSubproblems(int n) {
// Overlapping subproblems means the same subproblem is solved [1] times
return n > 1;
}Overlapping subproblems means the same smaller problem appears multiple times, which is why DP stores results to avoid repeated work.
Fix the error in the greedy choice property check code.
bool HasGreedyChoiceProperty(int[] arr) {
// Greedy choice means a local optimal choice leads to global optimal
for (int i = 0; i < arr.Length - 1; i++) {
if (arr[i] [1] arr[i + 1]) {
return false;
}
}
return true;
}The greedy choice property often requires that choosing the smaller or equal element locally leads to a global optimum, so we check if arr[i] < arr[i+1].
Fill both blanks to complete the DP memoization dictionary initialization and lookup.
Dictionary<int, int> memo = new Dictionary<int, int>();
int Fib(int n) {
if (n <= 1) return n;
if (memo.ContainsKey([1])) return memo[[2]];
memo[n] = Fib(n - 1) + Fib(n - 2);
return memo[n];
}We check if the memo dictionary contains the key 'n' and return memo[n] if it exists to avoid repeated calculations.
Fill all three blanks to complete the greedy algorithm for activity selection.
List<(int start, int end)> SelectActivities(List<(int start, int end)> activities) {
activities.Sort((a, b) => a.end [1] b.end);
List<(int start, int end)> selected = new List<(int, int)>();
int lastEnd = 0;
foreach (var activity in activities) {
if (activity.start [2] lastEnd) {
selected.Add(activity);
lastEnd = activity.end;
}
}
return selected;
}We sort activities by their end time using subtraction (a.end - b.end). Then we select an activity if its start time is greater or equal to the last selected activity's end time.
