From 0f2ce72be4fe35a029c2dea8c8facaead229c8a8 Mon Sep 17 00:00:00 2001 From: Rakshaa Viswanathan <46165429+rakshaa2000@users.noreply.github.com> Date: Tue, 1 Sep 2020 00:04:11 +0530 Subject: [PATCH] Created jumpgame.cpp An algorithm to check if you can reach the destination --- greedy_algorithms/jumpgame.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 greedy_algorithms/jumpgame.cpp diff --git a/greedy_algorithms/jumpgame.cpp b/greedy_algorithms/jumpgame.cpp new file mode 100644 index 000000000..f61e93d13 --- /dev/null +++ b/greedy_algorithms/jumpgame.cpp @@ -0,0 +1,21 @@ +//Jump Game: +/*Given an array of non-negative integers, you are initially positioned at the first index of the array. +Each element in the array represents your maximum jump length at that position. +Determine if you are able to reach the last index.*/ + +#include +bool canJump(vector& nums) { + int lastPos = nums.size() - 1; + for (int i = nums.size() - 1; i >= 0; i--) { + if (i + nums[i] >= lastPos) { + lastPos = i; + } + } + return lastPos == 0; +} + +void main(){ + //Sample test case + vector num={4,3,1,0,5}; + cout<