Greedy vs DP How to Know Which to Apply in DSA Java - Complexity Comparison
Choosing between Greedy and Dynamic Programming (DP) affects how fast your solution runs.
We want to know how the time cost changes depending on which method we pick.
Analyze the time complexity of these two approaches solving the same problem.
// Greedy approach example
int greedySolution(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
if (canTake(arr[i])) {
result += arr[i];
}
}
return result;
}
// DP approach example
int dpSolution(int[] arr) {
int n = arr.length;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = arr[0];
for (int i = 2; i <= n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + arr[i - 1]);
}
return dp[n];
}
The greedy method picks items quickly by a simple rule, while DP checks many combinations to find the best answer.
Look at the loops and repeated checks in each method.
- Greedy primary operation: One loop through the array, checking each item once.
- DP primary operation: One loop through the array, but each step uses previous results to decide best choice.
- How many times: Both run a single loop of size n, but DP does extra work inside the loop.
Both methods grow roughly with the size of the input array.
| Input Size (n) | Approx. Operations Greedy | Approx. Operations DP |
|---|---|---|
| 10 | ~10 checks | ~10 calculations |
| 100 | ~100 checks | ~100 calculations |
| 1000 | ~1000 checks | ~1000 calculations |
Pattern observation: Both grow linearly, but DP does slightly more work per step.
Time Complexity: O(n)
This means both methods take time proportional to the input size, but DP uses extra memory and calculations to find the best answer.
[X] Wrong: "Greedy always runs faster and is better than DP."
[OK] Correct: Greedy is faster but may give wrong answers if the problem needs checking many combinations, where DP shines.
Understanding when to use Greedy or DP shows you can pick the right tool for the problem, a key skill interviewers look for.
"What if the problem allowed overlapping subproblems but no greedy choice property? How would that affect which method to use and the time complexity?"
Practice
Solution
Step 1: Understand greedy choice property
A greedy algorithm works when choosing the best option at each step leads to a global optimum.Step 2: Recognize optimal substructure
Optimal substructure means the optimal solution can be built from optimal solutions of subproblems.Final Answer:
When the problem has the greedy choice property and optimal substructure -> Option DQuick Check:
Greedy = greedy choice + optimal substructure [OK]
- Confusing overlapping subproblems with greedy applicability
- Using greedy when problem needs full exploration
- Ignoring optimal substructure requirement
Solution
Step 1: Recall Java 2D array syntax
Java uses new int[rows][columns] to declare 2D arrays.Step 2: Check each option
int[][] dp = new int[5][5]; uses correct syntax. Options A, B, C have syntax errors or incomplete declarations.Final Answer:
int[][] dp = new int[5][5]; -> Option CQuick Check:
Correct 2D array declaration = int[][] dp = new int[5][5]; [OK]
- Using parentheses instead of brackets
- Missing size in second dimension
- Incorrect array initialization syntax
int[] coins = {1, 2, 5};
int amount = 11;
int count = 0;
for (int i = coins.length - 1; i >= 0; i--) {
count += amount / coins[i];
amount %= coins[i];
}
System.out.println(count);Solution
Step 1: Trace the loop from largest coin to smallest
Start with amount=11, coins = [1,2,5]. i=2 (coin=5): count += 11/5=2, amount=11%5=1.Step 2: Continue with next coins
i=1 (coin=2): count += 1/2=0, amount=1%2=1; i=0 (coin=1): count += 1/1=1, amount=1%1=0.Step 3: Calculate total count
Total count = 2 + 0 + 1 = 3.Final Answer:
3 -> Option AQuick Check:
Greedy coin count = 3 [OK]
- Adding counts incorrectly
- Mixing up division and modulo
- Ignoring order of coins
int[] coins = {1, 3, 4};
int amount = 6;
int count = 0;
for (int i = coins.length - 1; i >= 0; i--) {
count += amount / coins[i];
amount %= coins[i];
}
System.out.println(count);Solution
Step 1: Understand greedy choice property failure
Coins {1,3,4} do not guarantee greedy choice property for amount 6.Step 2: Trace greedy approach output
Greedy picks 4 once (count=1), remainder 2; then picks two 1s (count=3). But optimal is two 3s (count=2).Final Answer:
Greedy fails because coin set lacks greedy choice property -> Option BQuick Check:
Greedy fails if no greedy choice property [OK]
- Assuming greedy always works for coin change
- Ignoring optimal substructure requirement
- Confusing runtime errors with logic errors
class Task {
int start, end;
Task(int s, int e) { start = s; end = e; }
}Choose the correct approach and why.
Solution
Step 1: Identify problem type
This is the activity selection problem, classic greedy example.Step 2: Choose greedy approach
Sorting by earliest finish time ensures maximum tasks without overlap.Step 3: Compare options
Use greedy by sorting tasks by earliest finish time to select tasks matches known greedy solution; DP is possible but less efficient here.Final Answer:
Use greedy by sorting tasks by earliest finish time to select tasks -> Option AQuick Check:
Activity selection = greedy by finish time [OK]
- Sorting by start time or duration instead of finish time
- Using DP unnecessarily increasing complexity
- Ignoring greedy choice property in scheduling
Ready to prove it?
Pass the test and this pattern moves unknown
