π One-stop destination for all your technical interview Preparation π
Frog is on 1st position and wants to reach nth position. In one move, he can jump 1 position or 2 position ahead and the energy lost in those jump will be abs(iβth energy - i-1βth energy) or abs(iβth energy - i-2βth energy) accordingly. Find minimum energy required to reach the desired position (n).
f(0)=0
.f(i-1)+abs(h[i]-h[i-1])
.f(i-2)+abs(h[i]-h[i-2])
.int helper(int n, vector<int>& heights, int i)
{
if (i == 0) return 0;
int left = helper(n, heights, i - 1) + abs(heights[i - 1] - heights[i]);
int right = INT_MAX;
if (i > 1) right = helper(n, heights, i - 2) + abs(heights[i - 2] - heights[i]);
return min(left, right);
}
int frogJump(int n, vector<int>& heights)
{
return helper(n, heights, n - 1);
}
int helper(int n, vector<int>& heights, int i, vector<int>& memo)
{
if (i == 0) return 0;
if (memo[i] != -1) return memo[i]; // New code part
int left = helper(n, heights, i - 1, memo) + abs(heights[i - 1] - heights[i]);
int right = INT_MAX;
if (i > 1) right = helper(n, heights, i - 2, memo) + abs(heights[i - 2] - heights[i]);
return memo[i] = min(left, right); // New code part
}
int frogJump(int n, vector<int>& heights)
{
vector<int> memo(n + 1, -1); // New code part
return helper(n, heights, n - 1, memo);
}
int frogJump(int n, vector<int>& heights)
{
vector<int> dp(n, 0);
dp[0] = 0;
for (int i = 1; i < n; i++) {
int fs = dp[i - 1] + abs(heights[i] - heights[i - 1]);
int ss = INT_MAX;
if (i > 1) ss = dp[i - 2] + abs(heights[i] - heights[i - 2]);
dp[i] = min(fs, ss);
}
return dp[n - 1];
}
dp[i-1]=prev1
and dp[i-2]=prev2
and curr=min(fs,ss)
.return dp[n-1]
will be return prev1
.int frogJump(int n, vector<int>& heights)
{
int prev1 = 0;
int prev2 = 0;
for (int i = 1; i < n; i++) {
int fs = prev1 + abs(heights[i] - heights[i - 1]);
int ss = INT_MAX;
if (i > 1) ss = prev2 + abs(heights[i] - heights[i - 2]);
int curr = min(fs, ss);
prev2 = prev1;
prev1 = curr;
}
return prev1;
}