Each entry says how far you may jump forward from that position. The last position is guaranteed reachable.
Return the fewest jumps needed to get there from the first position.
jump({2, 3, 1, 1, 4})
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.
| 1 | int jump(const vector<int>& nums) { |
| 2 | |
| 3 | int n = nums.size(); |
| 4 | |
| 5 | int jumps = 1; |
| 6 | int edge = 0; |
| 7 | int farthest = 0; |
| 8 | |
| 9 | for (int i = 0; i + 1 <= n; i++) { |
| 10 | |
| 11 | farthest = max(farthest, i + nums[i]); |
| 12 | |
| 13 | if (i == edge) { |
| 14 | jumps++; |
| 15 | edge = farthest; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return jumps; |
| 20 | } |
| 1 | int jump(const vector<int>& nums) { |
| 2 | |
| 3 | int n = nums.size(); |
| 4 | |
| 5 | int jumps = 0; |
| 6 | int edge = 0; |
| 7 | int farthest = 0; |
| 8 | |
| 9 | for (int i = 0; i + 1 < n; i++) { |
| 10 | |
| 11 | farthest = max(farthest, i + nums[i]); |
| 12 | |
| 13 | if (i == edge) { |
| 14 | jumps++; |
| 15 | edge = farthest; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return jumps; |
| 20 | } |
| 1 | int jump(const vector<int>& nums) { |
| 2 | |
| 3 | int n = nums.size(); |
| 4 | |
| 5 | int jumps = 1; |
| 6 | int edge = 0; |
| 7 | int farthest = 0; |
| 8 | |
| 9 | for (int i = 0; i + 1 <= n; i++) { |
| 10 | |
| 11 | farthest = min(farthest, i + nums[i]); |
| 12 | |
| 13 | if (i == edge) { |
| 14 | jumps++; |
| 15 | edge = farthest; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return jumps; |
| 20 | } |