From b8b531815225a934308eb2c536bf42ef2a8ee13d Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Wed, 18 Oct 2023 12:18:06 -0700 Subject: [PATCH] day 19: 55-jump-game --- 55-jump-game/driver.cpp | 9 +++++++++ 55-jump-game/soln.cpp | 32 ++++++++++++++++++++++++++++++++ 55-jump-game/soln.hpp | 7 +++++++ 3 files changed, 48 insertions(+) create mode 100644 55-jump-game/driver.cpp create mode 100644 55-jump-game/soln.cpp create mode 100644 55-jump-game/soln.hpp 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