Back to the 2024 paper

Module 2: Fundamental Algorithmic Strategies

20247m

The 0/1 Knapsack Problem is a classical combinatorial optimization problem. Explain how this problem can be solved using:
(i) Brute-force method
(ii) Greedy method
(iii) Dynamic Programming
(iv) Branch-and-Bound
For each approach, explain the algorithm, time complexity, and limitations. Highlight why the greedy method may not always yield the optimal solution.

Worked SolutionAI Assisted

0/1 Knapsack via Dynamic Programming

Problem

Given nn items with profit pip_i, weight wiw_i, capacity WW, maximize ∑pixi\sum p_i x_i s.t. ∑wixi≤W\sum w_i x_i\le W, xi∈{0,1}x_i\in\{0,1\} (no fractional).

Optimal Substructure & Recurrence

Let dp[i][w]dp[i][w] = max profit using first ii items with capacity ww.
dp[0][w]=0,  dp[i][0]=0dp[i][w]={dp[i−1][w]wi>wmax⁡(dp[i−1][w],  dp[i−1][w−wi]+pi)wi≤w dp[0][w]=0,\; dp[i][0]=0\\ dp[i][w]=\begin{cases} dp[i-1][w] & w_i>w \\ \max(dp[i-1][w],\; dp[i-1][w-w_i]+p_i) & w_i\le w \end{cases}
Answer = dp[n][W]dp[n][W].

Algorithm

for w=0..W: dp[0][w]=0
for i=1..n:
  for w=0..W:
    if w_i <= w: dp[i][w]=max(dp[i-1][w], dp[i-1][w-w_i]+p_i)
    else dp[i][w]=dp[i-1][w]
// trace back to find chosen items

Time O(nW)O(nW) (pseudo-polynomial), Space O(nW)O(nW) → optimizable to O(W)O(W) with 1D array iterating ww descending.

Why DP vs Greedy

Fractional knapsack greedy by pi/wip_i/w_i is optimal O(nlog⁡n)O(n\log n), but 0/1 knapsack greedy fails (needs DP). Example earlier where greedy ratio fails, DP finds optimal.

Example (for Q90 values)

n=4n=4, p=(10,5,7,11)p=(10,5,7,11), w=(3,4,3,5)w=(3,4,3,5), W=15W=15 → total weight 15 if take all → profit 33 optimal. Table yields dp[4][15]=33dp[4][15]=33 (all items). Backtracking confirms inclusion of all.

Complexity

  • O(nW)O(nW) time, O(W)O(W) space optimized.
  • Not polynomial in input size (W may be exponential in bits) → pseudo-polynomial; problem is NP-hard.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.