[Baekjoon 12865] Ordinary Knapsack
A one-dimensional 0/1 knapsack DP that iterates weights backward to avoid selecting an item twice.
September 1, 2022
I defined dp[weight] as the maximum value attainable within that weight limit. For each item, compare the result of leaving it out with the result of including it.
dp[w] = max(dp[w], dp[w - itemWeight] + itemValue)
I updated weights from largest to smallest. If we iterate forward, a value updated for the current item can be reused later in the same pass, selecting that item more than once. The reverse iteration preserves the 0/1 constraint while reducing two-dimensional DP to one dimension.
Problem: Baekjoon · Code: View on GitHub