Skip to content

Commit a04ebd8

Browse files
committed
jump game - 45
1 parent 62ffa3d commit a04ebd8

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

include/leeter/jump_game_45.hpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <vector>
2+
3+
using std::vector;
4+
5+
namespace jump_game_45 {
6+
class Solution {
7+
public:
8+
int jump(vector<int>& nums) {
9+
int curr_jump = 0;
10+
int max_jump = 0;
11+
int jump_count = 0;
12+
for (int i = 0; i < nums.size() - 1; i++) {
13+
max_jump = std::max(max_jump, i + nums[i]);
14+
if (i == curr_jump) {
15+
curr_jump = max_jump;
16+
jump_count++;
17+
}
18+
if (curr_jump >= nums.size() - 1) {
19+
break;
20+
}
21+
}
22+
return jump_count;
23+
}
24+
};
25+
} // namespace jump_game_45

test/source/test_jump_45.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <doctest/doctest.h>
2+
3+
#include "leeter/jump_game_45.hpp"
4+
5+
TEST_CASE("jump game: test case 1") {
6+
vector<int> input = {2, 3, 1, 1, 4};
7+
jump_game_45::Solution sol;
8+
int output = sol.jump(input);
9+
CHECK(output == 2);
10+
}
11+
12+
TEST_CASE("jump game: test case 2") {
13+
vector<int> input = {2, 3, 0, 1, 4};
14+
jump_game_45::Solution sol;
15+
int output = sol.jump(input);
16+
CHECK(output == 2);
17+
}
18+
19+
// TEST_CASE("jump game: test case 3") {
20+
// vector<int> input = {2, 3, 0, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
21+
// jump_game_45::Solution sol;
22+
// int output = sol.jump(input);
23+
// CHECK(output == 4);
24+
// }

0 commit comments

Comments
 (0)