File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments