N, K = map(int, input().split()) A = tuple(map(int, input().split())) C = tuple(map(int, input().split())) dp = [[dict() for _ in range(N)] for _ in range(N)] ans = 0 for i in range(N): dp[i][i][C[i]] = A[i] ans = max(ans, dp[i][i][C[i]]) for k in range(N): for i in range(N): for c in dp[i][(i+k)%N]: if abs(c-C[(i+k+1)%N])<=K: if c not in dp[i][(i+k+1)%N]: dp[i][(i+k+1)%N][c] = 0 dp[i][(i+k+1)%N][c] = max(dp[i][(i+k+1)%N][c], dp[i][(i+k)%N][c]+A[(i+k+1)%N]) ans = max(ans, dp[i][(i+k+1)%N][c]) if C[(i+k+1)%N] not in dp[i][(i+k+1)%N]: dp[i][(i+k+1)%N][C[(i+k+1)%N]] = 0 dp[i][(i+k+1)%N][C[(i+k+1)%N]] = max(dp[i][(i+k+1)%N][C[(i+k+1)%N]], dp[i][(i+k)%N][c]+A[(i+k+1)%N]) ans = max(ans, dp[i][(i+k+1)%N][C[(i+k+1)%N]]) if abs(c-C[(i-1)%N])<=K: if c not in dp[(i-1)%N][(i+k)%N]: dp[(i-1)%N][(i+k)%N][c] = 0 dp[(i-1)%N][(i+k)%N][c] = max(dp[(i-1)%N][(i+k)%N][c], dp[i][(i+k)%N][c]+A[(i-1)%N]) ans = max(ans, dp[(i-1)%N][(i+k)%N][c]) if C[(i-1)%N] not in dp[(i-1)%N][(i+k)%N]: dp[(i-1)%N][(i+k)%N][C[(i-1)%N]] = 0 dp[(i-1)%N][(i+k)%N][C[(i-1)%N]] = max(dp[(i-1)%N][(i+k)%N][C[(i-1)%N]], dp[i][(i+k)%N][c]+A[(i-1)%N]) ans = max(ans, dp[(i-1)%N][(i+k)%N][C[(i-1)%N]]) #print(dp) print(ans)