Editorial for A Knapsack Problem


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: ji_mmyliu

This is the classical 0-1 Knapsack dynamic programming problem. Some resources that may be useful in familiarizing with the solution can be found below:

Time complexity: \mathcal{O}(NW).

Sample solution written in Python
N, W = map(int, input().split())
dp = [([0] * (W + 1)) for _ in range(N + 1)] # Empty 2D DP array
for i in range(1, N + 1):
    w, v = map(int, input().split())
    for j in range(W + 1):
        if j - w >= 0: # Check if there is space to take this piece
            # See if it is more optimal to take the piece of gold
            dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w] + v)
        else:
            dp[i][j] = dp[i - 1][j] # If it doesn't fit, use previous answer
print(dp[N][W])

Comments

There are no comments at the moment.