codekofi
← All questions

Jump Game

HardGreedy

The problem

Each entry says how far you may jump forward from that position — any distance up to that value, not exactly it.

Starting at the first position, return whether the last position is reachable.

canJump({2, 3, 1, 1, 4})

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1bool canJump(const vector<int>& nums) {
2
3 int n = nums.size();
4 int reach = 0;
5
6 for (int i = 0; i < n; i++) {
7
8 if (i > reach) {
9 return false;
10 }
11
12 reach = max(reach, i + nums[i]);
13 }
14
15 return true;
16}
1bool canJump(const vector<int>& nums) {
2
3 int n = nums.size();
4 int reach = 1;
5
6 for (int i = 0; i < n; i++) {
7
8 if (i > reach) {
9 return false;
10 }
11
12 reach = min(reach, i + nums[i]);
13 }
14
15 return true;
16}
1bool canJump(const vector<int>& nums) {
2
3 int n = nums.size();
4 int reach = 0;
5
6 for (int i = 0; i < n; i++) {
7
8 if (i > reach) {
9 return true;
10 }
11
12 reach = min(reach, i + nums[i]);
13 }
14
15 return true;
16}