Skip to content

Commit 534ef13

Browse files
authored
Merge pull request #45 from vipu18/patch-5
Implement space optimized Frog Jump solution
2 parents a414833 + 588a6b8 commit 534ef13

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <climits>
4+
#include <cmath>
5+
using namespace std;
6+
7+
// Space Optimized Solution
8+
class Solution {
9+
public:
10+
int frogJump(vector<int>& heights) {
11+
int n = heights.size();
12+
int prev = 0, prev2 = 0;
13+
for(int i = 1; i < n; i++) {
14+
int fs = prev + abs(heights[i] - heights[i-1]);
15+
int ss = INT_MAX;
16+
if(i > 1) ss = prev2 + abs(heights[i] - heights[i-2]);
17+
int curr = min(fs, ss);
18+
prev2 = prev;
19+
prev = curr;
20+
}
21+
return prev;
22+
}
23+
};
24+
25+
int main() {
26+
int n;
27+
cout << "Enter number of stones: ";
28+
cin >> n;
29+
vector<int> heights(n);
30+
cout << "Enter heights: ";
31+
for(int i = 0; i < n; ++i) {
32+
cin >> heights[i];
33+
}
34+
Solution sol;
35+
int result = sol.frogJump(heights);
36+
cout << "Minimum energy: " << result << endl;
37+
return 0;
38+
}

0 commit comments

Comments
 (0)