-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDP Frog Jump
More file actions
32 lines (28 loc) · 949 Bytes
/
Copy pathDP Frog Jump
File metadata and controls
32 lines (28 loc) · 949 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int minEnergy(const std::vector<int>& height, int n) {
// Handle base cases
if (n == 1) {
return 0;
} else if (n == 2) {
return abs(height[0] - height[1]);
}
// Initialize a DP table to store minimum energy to reach each stair
std::vector<int> dp(n + 1, std::numeric_limits<int>::max());
dp[1] = 0;
dp[2] = abs(height[0] - height[1]);
// Fill the DP table using bottom-up approach
for (int i = 3; i <= n; ++i) {
dp[i] = std::min(
dp[i - 1] + abs(height[i - 2] - height[i - 1]),
dp[i - 2] + abs(height[i - 3] - height[i - 1])
);
}
return dp[n];
}
//another approach
if(ind==0) return 0;
if(dp[ind]!=-1) return dp[ind];
int jumpTwo = INT_MAX;
int jumpOne= solve(ind-1, height,dp)+ abs(height[ind]-height[ind-1]);
if(ind>1)
jumpTwo = solve(ind-2, height,dp)+ abs(height[ind]-height[ind-2]);
return dp[ind]=min(jumpOne, jumpTwo);