CP: The most valuable bag

A thief has a bag that can carry weight W. There are n items, each with a weight and a value, and each can be taken at most once. Find the largest total value that fits in the bag.

What to build

Keep one array best of W + 1 values. For each item, loop the capacity c from W down to the item's weight and set best[c] = max(best[c], best[c - weight] + value). Print best[W].

Requirements

  • Use a single array and loop the capacity downwards
  • Each item is used at most once

Input

The first line has n and W. Each of the next n lines has weight value.

Output

The largest total value.

Constraints

1 ≤ n ≤ 100. 1 ≤ W ≤ 1000. Weights are from 1 to 1000 and values from 1 to 10⁶.

Example

Input:

4 10
5 10
4 40
6 30
3 50

Output:

90

Why it works

best[c] is the most value that fits in capacity c with the items seen so far. Going downwards means best[c - weight] has not yet been changed by this item, so the item is used at most once. The work is n × W steps.

Examples

Example 1 · Input
4 10
5 10
4 40
6 30
3 50
Expected output
90
Example 2 · Input
2 3
4 100
5 200
Expected output
0

Hints

Hint 1

vector<int> best(W + 1, 0);

Hint 2

For each item: for (int c = W; c >= wt; c--) best[c] = max(best[c], best[c - wt] + val);

Hint 3

Reading the answer from best[W] works because every best[c] means at most capacity c.

Solution

Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, W;
    cin >> n >> W;
    vector<long long> best(W + 1, 0);
    for (int i = 0; i < n; i++) {
        int wt;
        long long val;
        cin >> wt >> val;
        for (int c = W; c >= wt; c--)
            best[c] = max(best[c], best[c - wt] + val);
    }
    cout << best[W] << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Dynamic programming in contests →