CSES - Shared codeLink to this code:
https://cses.fi/paste/7d20f626ef506a6217af53/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ff first
#define ss second
int n, mxprice;
int helper(vector<int> &price, vector<int> &pages, int idx, int val, vector<vector<int>> &dp)
{
if (dp[idx][val] != -1) return dp[idx][val];
if (val == 0) return dp[idx][val] = 0;
if (idx == n) return dp[idx][val] = 0;
int op1, op2;
op1 = op2 = 0;
if (val - price[idx] >= 0) op1 = helper(price, pages, idx + 1, val - price[idx], dp) + pages[idx];
op2 = helper(price, pages, idx + 1, val, dp);
return dp[idx][val] = max(op1, op2);
}
void solve()
{
cin >> n >> mxprice;
vector<int> price(n);
for (int i = 0; i < n; i++) cin >> price[i];
vector<int> pages(n);
for (int i = 0; i < n; i++) cin >> pages[i];
vector<vector<int>> dp(n + 1, vector<int> (mxprice + 1, -1));
cout << helper(price, pages, 0, mxprice, dp) << endl;
}
int32_t main()
{
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// int t; cin >> t; while (t--)
{
solve();
}
return 0;
}