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-1): for i in range(N): for c in dp[i][(i+k)%N]: for j in range(N-k-1): for nc in dp[(i+k+1)%N][(i+k+1+j)%N]: if abs(c-nc)<=K: if c not in dp[i][(i+k+1+j)%N]: dp[i][(i+k+1+j)%N][c] = 0 dp[i][(i+k+1+j)%N][c] = max(dp[i][(i+k+1+j)%N][c], dp[i][(i+k)%N][c] + dp[(i+k+1)%N][(i+k+1+j)%N][nc]) ans = max(ans, dp[i][(i+k+1+j)%N][c]) if nc not in dp[i][(i+k+1+j)%N]: dp[i][(i+k+1+j)%N][nc] = 0 dp[i][(i+k+1+j)%N][nc] = max(dp[i][(i+k+1+j)%N][nc], dp[i][(i+k)%N][c] + dp[(i+k+1)%N][(i+k+1+j)%N][nc]) ans = max(ans, dp[i][(i+k+1+j)%N][nc]) for nc in dp[(i-1-j)%N][(i-1)%N]: if abs(c-nc)<=K: if c not in dp[(i-1-j)%N][(i+k)%N]: dp[(i-1-j)%N][(i+k)%N][c] = 0 dp[(i-1-j)%N][(i+k)%N][c] = max(dp[(i-1-j)%N][(i+k)%N][c], dp[i][(i+k)%N][c] + dp[(i-1-j)%N][(i-1)%N][nc]) ans = max(ans, dp[(i-1-j)%N][(i+k)%N][c]) if nc not in dp[(i-1-j)%N][(i+k)%N]: dp[(i-1-j)%N][(i+k)%N][nc] = 0 dp[(i-1-j)%N][(i+k)%N][nc] = max(dp[(i-1-j)%N][(i+k)%N][nc], dp[i][(i+k)%N][c] + dp[(i-1-j)%N][(i-1)%N][nc]) ans = max(ans, dp[(i-1-j)%N][(i+k)%N][nc]) #print(dp) print(ans)