mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Created jumpgame.cpp
An algorithm to check if you can reach the destination
This commit is contained in:
parent
072fc95228
commit
0f2ce72be4
21
greedy_algorithms/jumpgame.cpp
Normal file
21
greedy_algorithms/jumpgame.cpp
Normal file
@ -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 <vector.h>
|
||||
bool canJump(vector<int>& 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<int> num={4,3,1,0,5};
|
||||
cout<<canJump(num); //Should display true, as when you take one step from position 0, you reach position 1, from which 3 steps lead you to the destination
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user