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. int[] a = {10,30,20,40};
  13.  
  14. System.out.println("Test Case 1 Min Cost: " + minCostFrogJump(a));
  15.  
  16. int[] b = {30, 10, 60, 10, 60, 50};
  17.  
  18. System.out.println("Test Case 2 Min Cost: " + minCostFrogJump(b));
  19. }
  20.  
  21.  
  22. public static int minCostFrogJump(int[] height) {
  23. int n = height.length;
  24. if (n <= 1) return 0;
  25.  
  26. // dp[i] stores the minimum cost to reach stair i
  27. int[] dp = new int[n];
  28.  
  29. dp[0] = 0;
  30. dp[1] = Math.abs(height[1] - height[0]);
  31.  
  32. for(int i = 2; i<n; i++){
  33. int jumpOne = dp[i - 1] + Math.abs(height[i] - height[i - 1]);
  34. int jumpTwo = dp[i-2] +Math.abs(height[i] - height[i-2]);
  35.  
  36. dp[i] = Math.min(jumpOne,jumpTwo);
  37. }
  38.  
  39. return dp[n-1];
  40. }
  41. }
Success #stdin #stdout 0.14s 55592KB
stdin
Standard input is empty
stdout
Test Case 1 Min Cost: 30
Test Case 2 Min Cost: 40