Complete the code to check if a problem can be solved greedily by verifying if the problem has the greedy-choice property.
function canUseGreedy(problem) {
// Greedy works if local optimum leads to global optimum
return problem.hasGreedyChoiceProperty === [1];
}The greedy-choice property means choosing the best local option leads to the global best solution, so it must be true.
Complete the code to check if a problem has overlapping subproblems, a key property for dynamic programming.
function canUseDP(problem) {
// DP works if subproblems repeat
return problem.hasOverlappingSubproblems === [1];
}Dynamic programming requires overlapping subproblems to reuse solutions and avoid repeated work.
Fix the error in the function that decides which approach to use based on problem properties.
function chooseApproach(problem) {
if (problem.hasGreedyChoiceProperty === [1] && problem.hasOverlappingSubproblems === false) {
return 'Greedy';
} else if (problem.hasOverlappingSubproblems === true) {
return 'DP';
} else {
return 'Brute Force';
}
}The greedy approach applies when the greedy-choice property is true and overlapping subproblems is false.
Fill both blanks to complete the function that explains why greedy or DP is chosen.
function explainChoice(problem) {
if (problem.hasGreedyChoiceProperty === [1]) {
return 'Use greedy because it has the greedy-choice property.';
} else if (problem.hasOverlappingSubproblems === [2]) {
return 'Use DP because it has overlapping subproblems.';
} else {
return 'Use brute force as no special properties found.';
}
}Greedy is chosen if greedy-choice property is true; DP if overlapping subproblems is true.
Fill all three blanks to complete the function that returns the recommended approach based on problem properties.
function recommendApproach(problem) {
if (problem.hasGreedyChoiceProperty === [1] && problem.hasOverlappingSubproblems === [2]) {
return [3];
} else if (problem.hasGreedyChoiceProperty === true) {
return 'Greedy';
} else if (problem.hasOverlappingSubproblems === true) {
return 'DP';
} else {
return 'Brute Force';
}
}If neither greedy-choice property nor overlapping subproblems is true, recommend brute force.
