Complete the code to check if the problem has optimal substructure property.
if (problem.has[1]()) { System.out.println("Optimal substructure exists"); }
The optimal substructure property means the optimal solution can be built from optimal solutions of subproblems.
Complete the code to check if the problem has greedy choice property.
if (problem.has[1]()) { System.out.println("Greedy choice property exists"); }
The greedy choice property means a global optimal solution can be arrived at by choosing a local optimum at each step.
Fix the error in the code that decides whether to use greedy or DP.
if (problem.hasOptimalSubstructure() && problem.has[1]()) { System.out.println("Use Greedy Algorithm"); } else if (problem.hasOptimalSubstructure() && problem.hasOverlappingSubproblems()) { System.out.println("Use Dynamic Programming"); }
Greedy algorithms require both optimal substructure and greedy choice property.
Fill both blanks to complete the method that decides algorithm type based on problem properties.
public String chooseAlgorithm(Problem problem) {
if (problem.hasOptimalSubstructure() && problem.has[1]()) {
return "Greedy";
} else if (problem.hasOptimalSubstructure() && problem.has[2]()) {
return "Dynamic Programming";
} else {
return "No suitable algorithm";
}
}Greedy algorithms need greedy choice property; dynamic programming needs overlapping subproblems.
Fill all three blanks to complete the code that explains when to use greedy or DP.
public void explainChoice(Problem problem) {
if (problem.hasOptimalSubstructure() && problem.has[1]()) {
System.out.println("Use Greedy because it has [2] and [3].");
} else if (problem.hasOptimalSubstructure() && problem.hasOverlappingSubproblems()) {
System.out.println("Use Dynamic Programming because it has overlapping subproblems and optimal substructure.");
} else {
System.out.println("Neither greedy nor DP is suitable.");
}
}Greedy algorithms require both greedy choice property and optimal substructure.
