CSES Solution
Book Shop | Dynamic Programming
You are in a book shop which sells n different books. You know the price and number of pages of each book.
You have decided that the total price of your purchases will be at most x. What is the maximum number of pages you can buy? You can buy each book at most once.
Input
The first input line contains two integers n and x: the number of books and the maximum total price.
The next line contains n integers h1,h2,…,hn: the price of each book.
The last line contains n integers s1,s2,…,sn: the number of pages of each book.
Output
Print one integer: the maximum number of pages.
Solution Code:
#include
using namespace std;
const int maxN = 1000;
const int maxX = 1e5;
int N, X, h[maxN], s[maxN], dp[maxX+1];
int main(){
scanf("%d %d", &N, &X);
for(int i = 0; i < N; i++) scanf("%d", &h[i]);
for(int i = 0; i < N; i++) scanf("%d", &s[i]);
fill(dp+1, dp+X+1, -1);
for(int i = 0; i < N; i++)
for(int j = X-h[i]; j >= 0; j--)
if(dp[j] != -1)
dp[j+h[i]] = max(dp[j+h[i]], dp[j]+s[i]);
for(int i = 1; i <= X; i++)
dp[i] = max(dp[i], dp[i-1]);
printf("%d\n", dp[X]);
}