Skip to content

Commit 9bbb2fd

Browse files
committed
fix: use previous algorithm
1 parent 4a3e7bb commit 9bbb2fd

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

greedy_algorithms/jump_game.cpp

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,14 @@ namespace greedy_algorithms {
4040
* @returns false if the index can NOT be reached
4141
*/
4242
template <typename T>
43-
bool can_jump(const std::vector<T> &nums, const int &index = 1) {
44-
const int size = nums.size() + 1 - nums[index];
45-
if (nums[index] >= size) { // `>=` because the number can be higher than the size of the array.
46-
return true;
43+
bool can_jump(const std::vector<T> &nums) {
44+
size_t lastPos = nums.size() - 1;
45+
for (int i = nums.size() - 1; i >= 0; i--) {
46+
if (i + nums[i] >= lastPos) {
47+
lastPos = i;
48+
}
4749
}
48-
return false;
50+
return lastPos == 0;
4951
}
5052
} // namespace greedy_algorithms
5153

@@ -67,11 +69,11 @@ static void test() {
6769
assert(greedy_algorithms::can_jump(nums) == true);
6870

6971
// 4th test
70-
nums = { 4, 2, 8, 9, 6 };
72+
nums = { 1, 0, 5, 8, 12 };
7173
assert(greedy_algorithms::can_jump(nums) == false);
7274

7375
// 5th test
74-
nums = { 7, 4, 8, 13, 2, 11 };
76+
nums = {2, 1, 4, 7};
7577
assert(greedy_algorithms::can_jump(nums) == true);
7678

7779
std::cout << "All tests have successfully passed!\n";

0 commit comments

Comments
 (0)