All problems

Problem 188

0/1 Knapsack

Medium · 20 pts · Array, Dynamic Programming

Problem

You have N items. Item i has weight W[i] and value V[i]. Your bag holds a total weight of at most C. Each item can be taken at most once (or not at all), and items cannot be split. Find the largest total value you can carry. Use dynamic programming over capacities: best[c] is the most value that fits in capacity c. For each item, update best[c] = max(best[c], best[c - W[i]] + V[i]) for c going down from C to W[i]; going downward ensures each item is used at most once. Values can add up beyond the 32-bit range.

Input

First line: integers N and C. Next N lines: W[i] and V[i].

Output

Print the maximum total value.

Constraints

1 <= N <= 100; 1 <= C <= 100000; 1 <= W[i] <= 100000; 0 <= V[i] <= 1000000000

Example input

3 4
1 15
3 20
4 30

Example output

35

Explanation

The capacity is 4. Taking the items of weight 1 (value 15) and weight 3 (value 20) uses exactly 4 and is worth 35. The single item of weight 4 is worth only 30, so the answer is 35.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Edit Distance Next: Unique Paths