Knapsack (0/1 and unbounded)

rock, electric guitar, powerful, anthem

Listen on 93

Lyrics

[Verse 1]
Pack your bag but weight's a limit, every item has a choice
Take it once or leave it sitting, that's the zero-one voice
Thief creeps through the mansion scanning, jewels and gold in sight
Each treasure gets one judgment call, grab it once or pass it by
Dynamic table tracks the values, bottom up we calculate
Previous row holds the wisdom, current choice we contemplate

[Chorus]
Knapsack zero-one, each item once and done
Check the weight, maximize the sum
Unbounded means infinity, grab it endlessly
Same item, different strategy
Memo-ize the sub-problems, build solutions from the ground
Optimization algorithms, best combinations to be found

[Verse 2]
Unbounded changes everything, same item multiple times
Coins for change or rods for cutting, repetition paradigm
For each weight check every item, can I fit it one more time
Add its value to remainder, recursive by design
Base cases catch the boundaries, when capacity hits zero
Memoization saves the answers, computational hero

[Chorus]
Knapsack zero-one, each item once and done
Check the weight, maximize the sum
Unbounded means infinity, grab it endlessly
Same item, different strategy
Memo-ize the sub-problems, build solutions from the ground
Optimization algorithms, best combinations to be found

[Bridge]
Bottom-up builds the matrix, row by row we ascend
Top-down with memorization, recursive calls defend
Space complexity matters, can we optimize the grid
One dimension holds the current, previous gets forbid

[Verse 3]
Fractional breaks the paradigm, split items by their weight
Greedy works when pieces allowed, value per unit rate
But integer constraints demand the dynamic programming way
Substructure optimal property, overlapping saves the day
From coin change to subset sums, the pattern stays the same
Weight capacity, value targets, different names same game

[Outro]
Pack it tight, pack it right
Zero-one or infinite sight
DP solves what greedy can't
Optimal substructure's chant

← Longest increasing subsequence | Matrix chain multiplication →