Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 474 Ones and Zeroes - Walkthrough

2D knapsack trace

Trace Ones and Zeroes with strings ["10","0001","111001","1","0"][\text{"10"}, \text{"0001"}, \text{"111001"}, \text{"1"}, \text{"0"}], m=5m=5 zeros, n=3n=3 ones. Each string has a cost (zeros,ones)(zeros, ones): (1,1)(1,1), (3,1)(3,1), (2,4)(2,4), (0,1)(0,1), (1,0)(1,0). DP is dp[i][j]dp[i][j] = max strings with ii zeros and jj ones. Process strings like 0/1 Knapsack but with 2D capacity. Optimal: take "10" (1,1)(1,1), "0001" (3,1)(3,1), "1" (0,1)(0,1), "0" (1,0)(1,0) = total (5,3)(5, 3) which fits in (5,3)(5, 3).

Answer: 44 strings.