#include using namespace std; using ll = long long; template istream& operator >> (istream& is, vector& vec) { for(T& x : vec) is >> x; return is; } int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, k, n2; cin >> n >> k; n2 = 2 * n; vector a(n), c(n); ll sa[n2 + 1] = {}, dp[n2][n2 + 1] = {}, dp2[n2][n2 + 1] = {}, S; cin >> a >> c; a.insert(a.end(), a.begin(), a.end()); c.insert(c.end(), c.begin(), c.end()); for(int i = 0; i < n2; i++){ sa[i + 1] = sa[i] + a[i]; dp[i][i + 1] = dp2[i][i + 1] = S = 1ll << --c[i]; for(int j = 1; j <= k; j++){ dp2[i][i + 1] |= (S >> j) | (S << j); } } ll ans = *max_element(a.begin(), a.end()); for(int len = 2; len <= n; len++){ for(int l = 0; l + len < n2; l++){ int r = l + len; for(int m = l + 1; m < r; m++){ dp[l][r] |= (dp[l][m] & dp2[m][r]) | (dp2[l][m] & dp[m][r]); } if(dp[l][r]){ ans = max(ans, sa[r] - sa[l]); dp2[l][r] = dp[l][r]; for(int i = 1; i <= k; i++){ dp2[l][r] |= (dp[l][r] >> i) | (dp[l][r] << i); } } } } cout << ans << '\n'; }