fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. long[] b=new long[n+1];
  8. for(int i=1;i<=n;i++){
  9. b[i]=sc.nextLong();
  10. }
  11. long[] dp=new long[n+1];
  12. //storing the best difference so far
  13. dp[0]=0;
  14. dp[1]=Math.abs(b[1]-b[2]);
  15. for(int i=3;i<=n;i++){
  16. //for each ith stone, i can reach there from i-1 or i-2 stone
  17. //for i-1 stone u have to first add up the dp[i-1] value there
  18. //then add ith stones difference from i-1
  19. dp[i]=Math.min(dp[i-1]+Math.abs(b[i]-b[i-1]),dp[i-2]+Math.abs(b[i]-b[i-2]));
  20. }
  21. System.out.println(dp[n]);
  22. }
  23. }
  24.  
Success #stdin #stdout 0.25s 36548KB
stdin

4
10 30 40 20
stdout
10