day 19: 55-jump-game

This commit is contained in:
Kaushik Narayan R 2023-10-18 12:18:06 -07:00
parent 9ad7de8dd5
commit b8b5318152
3 changed files with 48 additions and 0 deletions

9
55-jump-game/driver.cpp Normal file
View File

@ -0,0 +1,9 @@
#include "soln.hpp"
int main() {
vector<int> nums = {3,2,1,0,4};
bool answer = false;
Solution soln;
cout << "Checked if can jump correctly? " << soln.test(nums, answer) << endl;
return 0;
}

32
55-jump-game/soln.cpp Normal file
View File

@ -0,0 +1,32 @@
#include "soln.hpp"
bool Solution::canJump(vector<int> &nums)
{
int n = nums.size();
int cur_pos = n - 2;
int gaps = 0;
int next_connect = n - 1;
// base cases
if (n == 1)
return true;
if (nums[0] == 0)
return false;
// track last known connection to get to end
while (cur_pos >= 0)
{
if (cur_pos + nums[cur_pos] >= next_connect)
{
gaps = 0;
next_connect = cur_pos;
}
else
gaps++;
cur_pos--;
}
return gaps == 0;
}
bool Solution::test(vector<int> &nums, bool answer)
{
return canJump(nums) == answer;
}

7
55-jump-game/soln.hpp Normal file
View File

@ -0,0 +1,7 @@
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums);
bool test(vector<int>& nums, bool answer);
};