Advancing through an Array

 

#include <iostream>
#include <vector>
using namespace std;


bool canReachEnd(vector<int>& v) {
int last_index = v.size()-1;
int furthest_index = 0;
for (int i = 0; i <= furthest_index && furthest_index < last_index; i++) {
furthest_index = max(furthest_index, i + v[i]);
}
return (furthest_index >= last_index);
}

int main()
{
vector<int> v = { 3,2,0,0,2,0,1 };
bool result = canReachEnd(v);
if (result) {
cout << "We can reach the end of array.\n";
}
else {
cout << "We can't reach the end of array.\n";
}
}

Comments

Popular posts from this blog

Clear right most set bit of an integer n

Swap bits at ith and jth position of integer n

Toggle the bit at Kth position of integer n