Q-3 Frog Jump - Coding Ninjas
Tue Aug 01 2023 06:43:57 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
import java.util.* ;
import java.io.*;
public class Solution {
public static int frogJump(int n, int heights[]) {
// return s(heights , n-1 , new Integer[n]);
int[] dp = new int[n];
dp[0] = 0;
for(int i= 1 ;i < n ;i++){
int one = Integer.MAX_VALUE , two = Integer.MAX_VALUE;
if(i-1 >= 0)
one = Math.abs(heights[i] - heights[i-1]) + dp[i-1];
if(i-2 >= 0)
two = Math.abs(heights[i] - heights[i-2]) + dp[i-2];
dp[i] = Math.min(one , two);
}
return dp[n-1];
}
public static int s(int heights[], int n , Integer[] dp){
if(n == 0)
return 0;
if(dp[n] != null)
return dp[n];
int one = Integer.MAX_VALUE , two = Integer.MAX_VALUE;
if(n-1 >= 0)
one = Math.abs(heights[n] - heights[n-1]) + s(heights , n-1 , dp);
if(n-2 >= 0)
two = Math.abs(heights[n] - heights[n-2]) + s(heights , n-2 , dp);
return dp[n] = Math.min(one , two);
}
}
content_copyCOPY
https://www.codingninjas.com/studio/problems/frog-jump_3621012
Comments