-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrogJumpsMinEnergy.cpp
84 lines (67 loc) · 2.1 KB
/
frogJumpsMinEnergy.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<bits/stdc++.h>
using namespace std;
// * Recursive Approach
// * T.C : Exponential - O(2^n) and S.C : O(N) - Recursive Call Stack space
int helper(int idx, vector<int> &heights) {
if(idx == 0)
return 0;
int left = helper(idx-1, heights) + abs(heights[idx] - heights[idx-1]);
int right = INT_MAX;
if(idx > 1)
right = helper(idx-2, heights) + abs(heights[idx] - heights[idx-2]);
return min(left,right);
}
int frogJumps(int n, vector<int> heights) {
return helper(n-1, heights);
}
// * MEMOIZATION -> Saving the Recomputation Time using DP Array
int helper(vector<int> &heights, int i, vector<int> & dp) {
if(i <= 0)
return 0;
if(dp[i] != -1)
return dp[i];
int left = helper(heights, i-1, dp) + abs(heights[i] - heights[i-1]);
int right = INT_MAX;
if(i > 1)
right = helper(heights, i-2, dp) + abs(heights[i] - heights[i-2]);
return dp[i] = min(left, right);
}
int frogJumpMemo(int n, vector<int> &heights)
{
vector<int> dp(n+1, -1);
return helper(heights, n-1, dp);
}
// * TABULATION -> BOTTOM UP Approach
int frogJumpsTab(int n, vector<int> &heights) {
vector<int> dp(n+1, -1);
dp[0] = 0;
// * Iterative Solution
for(int i = 1; i < n; i++) {
int firstStep = dp[i-1] + abs(heights[i] - heights[i-1]);
int secondStep = INT_MAX;
if(i > 1)
secondStep = dp[i-2] + abs(heights[i] - heights[i-2]);
dp[i] = min(firstStep,secondStep);
}
return dp[n-1];
}
// * Space Optimization with TABULATION
int frogJumpsTabSpaceOptimized(int n, vector<int> heights) {
int prevEle = 0, prevEle2 = 0;
for(int i = 1; i < n; i++) {
int firstStep = prevEle + abs(heights[i] - heights[i-1]);
int secondStep = INT_MAX;
if(i > 1)
secondStep = prevEle2 + abs(heights[i] - heights[i-2]);
int currEle = min(firstStep,secondStep);
prevEle2 = prevEle;
prevEle = currEle;
}
// * In every turn we need to find the most
return prevEle;
}
int main()
{
cout << "Min Energy required is: " << frogJumpsTabSpaceOptimized(6,{30,10,60,10,60,50}) << endl;
return 0;
}