Funcia
Lv.2arraybfsgreedy

Minimum Jumps

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Stones are laid in a row; from stone i you may jump forward to any stone from i + 1 to i + nums[i]. Starting at stone 0, return the minimum number of jumps to reach the last stone (n - 1), or -1 if it cannot be reached (0 if n = 1).

Examples

numsresult
[2, 3, 1, 1, 4]2
[3, 2, 1, 0, 4]-1
[0]0

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[]) → int

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000
  • 0≤0 \le nums[i] ≤100,000\le 100{,}000

Expected complexity

Time
O(N)
Space
O(1)

Examples

numsExpected
[2,3,1,1,4]2
[3,2,1,0,4]-1
[0]0

Hint

Hint

Think BFS over ranges: the stones reachable with k + 1 jumps end at the farthest i + nums[i] over the range reachable with k jumps. Track end, far and jumps in one pass. Relaxing every reachable cell from every stone is O(N⋅max⁡(nums))O(N \cdot \max(nums)) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251018 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4011verdict only
performance605verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.