fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner sc = new Scanner(System.in);
  14. int n =sc.nextInt();
  15. int dp[] = new int[n];
  16. int cost[] = new int[n];
  17.  
  18. for(int i =0;i<n;i++){
  19. cost[i] = sc.nextInt();
  20. }
  21. dp[0] = 0;
  22. dp[1] = Math.abs(cost[1] - cost[0]);
  23. for(int i=2;i<n;i++){
  24. int ans = Integer.MAX_VALUE;
  25. ans = Math.min(ans,Math.abs(cost[i]-cost[i-1])+dp[i-1]);
  26. if(i>=3){
  27. ans = Math.min(ans,Math.abs(cost[i]-cost[i-3])+dp[i-3]);
  28. }
  29. dp[i] =ans;
  30. }
  31. System.out.println(dp[n-1]);
  32. }
  33. }
Success #stdin #stdout 0.11s 54452KB
stdin
6
4 12 13 18 10 12
stdout
10