Dynamic Programming & Greedy Approach
Dynamic Programming & Greedy Approach
Descriptive Answers
1) Binomial Coefficients using Dynamic Programming
Binomial Coefficients (C(n, k)) count the number of ways to choose k elements from a set of
n elements. It is defined as:
This recursive relation arises from Pascal's Triangle. Using Dynamic Programming, we store
previously computed values in a 2D array C[n+1][k+1] to avoid redundant computations.
DP Algorithm:
for i from 0 to n:
for j from 0 to min(i, k):
if j == 0 or j == i:
C[i][j] = 1
else:
C[i][j] = C[i-1][j-1] + C[i-1][j]
2) Floyd’s Algorithm
Floyd’s Algorithm finds shortest paths between all pairs of vertices in a weighted graph. It
uses a dynamic programming approach.
Recursive Formula:
Let D[i][j][k] be the shortest path from i to j using intermediate vertices from 1 to k.
D[i][j][k] = min(D[i][j][k-1], D[i][k][k-1] + D[k][j][k-1])
Example:
For a graph with 3 vertices:
0 5 INF
INF 0 3
2 INF 0
After applying Floyd’s algorithm, shortest paths between all pairs are found.
Let m[i][j] be the minimum number of scalar multiplications needed to compute Ai...Aj.
Recursive Formula:
m[i][j] = 0 if i == j
m[i][j] = min over i <= k < j of {m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]}
Cost Function:
e[i][j] = min over i <= r <= j of {e[i][r-1] + e[r+1][j] + w[i][j]}
Recursive Formula:
if wt[i-1] <= W:
dp[i][W] = max(val[i-1] + dp[i-1][W-wt[i-1]], dp[i-1][W])
else:
dp[i][W] = dp[i-1][W]
Iterative DP:
for i from 0 to n:
for w from 0 to W:
if i==0 or w==0:
dp[i][w] = 0
else if wt[i-1] <= w:
dp[i][w] = max(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
Kruskal’s Algorithm:
- Sorts all edges and adds the smallest edge without forming a cycle.
- Uses Disjoint Set (Union-Find).
- Time: O(E log E)
Greedy Nature:
Both are greedy algorithms as they make locally optimal choices to find the global optimum.
Greedy: Always pick the largest denomination <= remaining amount. May fail if
denominations are non-standard.
Example:
Coins = [1, 3, 4], Amount = 6
- Greedy: 4+1+1 = 3 coins
- DP: 3+3 = 2 coins (optimal)