diff --git a/55-jump-game/driver.cpp b/55-jump-game/driver.cpp new file mode 100644 index 0000000..1f49b88 --- /dev/null +++ b/55-jump-game/driver.cpp @@ -0,0 +1,9 @@ +#include "soln.hpp" + +int main() { + vector nums = {3,2,1,0,4}; + bool answer = false; + Solution soln; + cout << "Checked if can jump correctly? " << soln.test(nums, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/55-jump-game/soln.cpp b/55-jump-game/soln.cpp new file mode 100644 index 0000000..43041e7 --- /dev/null +++ b/55-jump-game/soln.cpp @@ -0,0 +1,32 @@ +#include "soln.hpp" + +bool Solution::canJump(vector &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 &nums, bool answer) +{ + return canJump(nums) == answer; +} \ No newline at end of file diff --git a/55-jump-game/soln.hpp b/55-jump-game/soln.hpp new file mode 100644 index 0000000..75fbd96 --- /dev/null +++ b/55-jump-game/soln.hpp @@ -0,0 +1,7 @@ +#include +using namespace std; +class Solution { +public: + bool canJump(vector& nums); + bool test(vector& nums, bool answer); +}; \ No newline at end of file