public int minimumEnergy(int[] time, int[] position) {
int n = time.length;
int m = position.length;
int[] dp = new int[n + 1][m + 1];
for (int t = 1; t <= n; t++) {
for (int p = 1; p <= m; p++) {
if (time[t - 1] <= position[p - 1] && time[t - 1] <= position[p]) {
dp[t][p] = min(dp[t - 1][p], dp[t - 1][p - 1] + 1, dp[t - 1][p + 1] + 1);
} else if (time[t - 1] <= position[p]) {
dp[t][p] = min(dp[t - 1][p] + 2, dp[t - 1][p - 1] + 3, dp[t - 1][p + 1] + 3);
} else {
dp[t][p] = dp[t - 1][p] + 2;
}
}
}
return min(dp[n][1], dp[n][2], dp[n][m]);
}
}