Skip to lesson

Topic set: greedy and DP

Greedy algorithms and Dynamic Programming both solve optimization problems. We learn to identify when local choices yield global optimality and when subproblem memoization is mandatory.

Greedy choice property versus optimal substructure

Optimization problems require finding the minimum, maximum, or count of valid solutions. A greedy algorithm builds a solution piece-by-piece, always selecting the choice that appears best at that exact moment, without ever reconsidering earlier decisions.

Example 1 · Greedy Interval Scheduling Maximization

IntervalSchedulingGreedyDemo.javaJava
import java.util.*;
public class IntervalSchedulingGreedyDemo {    public static int maxNonOverlapping(int[][] intervals) {        if (intervals == null || intervals.length == 0) return 0;        // Sort by end time ascending        Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
        int count = 1;        int end = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {            if (intervals[i][0] >= end) {                count++;                end = intervals[i][1];            }        }        return count;    }
    public static void main(String[] args) {        int[][] intervals = {{1, 3}, {2, 4}, {3, 5}, {0, 6}, {5, 7}};        System.out.println("Max non-overlapping: " + maxNonOverlapping(intervals));    }}
Output
Max non-overlapping: 3

What this code does

  • Intervals selected are [1, 3], [3, 5], and [5, 7].
  • Sorting by earliest end time maximizes remaining availability.
  • Runs in O(N log N) time due to sorting and O(1) auxiliary space.

When the greedy choice property holds—such as selecting non-overlapping intervals by earliest finish time, or jumping to the farthest reachable index—greedy algorithms run in blazing O(N) or O(N log N) time with O(1) extra space. However, if choices have future consequences or resource constraints (e.g. 0/1 Knapsack or Coin Change with arbitrary denominations), greedy makes suboptimal choices and fails. When greedy fails, plain recursion evaluates all 2^N combinations, which times out exponentially. Dynamic Programming solves this by recognizing overlapping subproblems. By caching solutions in an array or table, DP reduces exponential 2^N time down to polynomial time like O(N * W).

1D and 2D DP state representation

Dynamic Programming models problems through state definitions and transition recurrences. In 1D DP problems like House Robber or Coin Change, state dp[i] represents the optimal answer using a prefix of items or reaching target amount i.

Example 2 · Coin Change Minimum Coins via 1D DP

CoinChangeDpDemo.javaJava
import java.util.*;
public class CoinChangeDpDemo {    public static int coinChange(int[] coins, int amount) {        int[] dp = new int[amount + 1];        Arrays.fill(dp, amount + 1);        dp[0] = 0;
        for (int c : coins) {            for (int a = c; a <= amount; a++) {                dp[a] = Math.min(dp[a], dp[a - c] + 1);            }        }        return dp[amount] > amount ? -1 : dp[amount];    }
    public static void main(String[] args) {        int[] coins1 = {1, 2, 5};        System.out.println("Coins for 11: " + coinChange(coins1, 11)); // 5 + 5 + 1 = 3        int[] coins2 = {2};        System.out.println("Coins for 3: " + coinChange(coins2, 3));   // -1    }}
Output
Coins for 11: 3
Coins for 3: -1

What this code does

  • Amount 11 requires 3 coins (5 + 5 + 1).
  • Amount 3 cannot be formed with denomination 2, returning -1.
  • Iterates amount forward in O(N * A) time and O(A) auxiliary space.

Transitions inspect immediate predecessor states: for House Robber, dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]). In 2D DP problems—such as 0/1 Knapsack (items and capacity) or Longest Common Subsequence (prefixes of strings s1 and s2)—the state dp[i][j] tracks two interacting parameters. A critical optimization is space reduction. If transition dp[i][j] only depends on row i - 1, we can compress the 2D matrix into a 1D array of size O(W). For 0/1 Knapsack, iterating capacity backwards (from W down to wt[i]) prevents using the same item multiple times while cutting memory consumption from O(N * W) down to O(W).

Discerning greedy from DP under interview pressure

Under the pressure of a 45-minute technical interview, deciding between Greedy and DP is one of the most stressful forks in the road. You can systematically make the right choice by testing two criteria.

First, test for local independence: does making a greedy choice right now preclude you from making a better choice later? Try creating a small 3-element counterexample. For example, with coin denominations [1, 3, 4] and target 6, greedy picks 4 + 1 + 1 (3 coins), whereas the optimal choice is 3 + 3 (2 coins). The counterexample proves greedy is flawed, so DP is mandatory.

Second, examine the constraints. If N <= 10^5 and the problem asks for interval scheduling or activity selection, it is almost certainly Greedy (sorting in O(N log N)). If constraints are smaller (N <= 1000, W <= 1000) and ask for min/max combinations, Dynamic Programming is the expected solution.

Interval scheduling and partition patterns

Interval problems are among the most frequent greedy and DP patterns in top tech rounds. They divide into two fundamental paradigms based on whether overlapping intervals are merged or counted.

Example 3 · Meeting Rooms II via Min-Heap

MeetingRoomsMinHeapDemo.javaJava
import java.util.*;
public class MeetingRoomsMinHeapDemo {    public static int minMeetingRooms(int[][] intervals) {        if (intervals == null || intervals.length == 0) return 0;        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        PriorityQueue<Integer> endTimes = new PriorityQueue<>();        endTimes.offer(intervals[0][1]);
        for (int i = 1; i < intervals.length; i++) {            if (intervals[i][0] >= endTimes.peek()) {                endTimes.poll(); // Room is freed up            }            endTimes.offer(intervals[i][1]);        }        return endTimes.size();    }
    public static void main(String[] args) {        int[][] meetings = {{0, 30}, {5, 10}, {15, 20}};        System.out.println("Min meeting rooms: " + minMeetingRooms(meetings));    }}
Output
Min meeting rooms: 2

What this code does

  • [0, 30] overlaps with [5, 10], requiring 2 rooms.
  • [15, 20] starts after [5, 10] ends, reusing room 2.
  • Total rooms needed is 2, running in O(N log N) time.

Interval Scheduling Maximization asks for the maximum number of mutually compatible intervals. Sorting by end time is provably optimal: picking the interval that finishes earliest leaves the maximum possible remaining time for future intervals, running in O(N log N) time. Meeting Rooms asks for the minimum number of conference rooms required to hold all meetings without collisions. We sort meetings by start time and maintain a min-heap of active meeting end times. If the earliest ending meeting finishes before the next meeting begins, we reuse the room by polling; otherwise, we allocate a new room. The heap size at the end gives the exact room count in O(N log N) time.

Next step

Check your understanding

10 quick questions