fork download
  1. public class Main {
  2. public static void main(String[] args) {
  3. int n = 6;
  4. long k = 3;
  5. long[] b = {0, 10, 30, 20, 50, 40, 60};
  6.  
  7. long[] dp = new long[n + 1];
  8. for (int i = 1; i <= n; i++) {
  9. dp[i] = Long.MAX_VALUE;
  10. }
  11.  
  12. dp[1] = 0;
  13. dp[2] = Math.abs(b[1] - b[2]);
  14.  
  15. for (int i = 3; i <= n; i++) {
  16. for (int j = 1; j <= k && i - j >= 1; j++) {
  17. dp[i] = Math.min(dp[i], dp[i - j] + Math.abs(b[i] - b[i - j]));
  18. }
  19. }
  20.  
  21. System.out.println("Minimum cost to reach last step: " + dp[n]);
  22. }
  23. }
  24.  
Success #stdin #stdout 0.1s 55556KB
stdin
Standard input is empty
stdout
Minimum cost to reach last step: 50