42 lines
No EOL
1.3 KiB
Kotlin
42 lines
No EOL
1.3 KiB
Kotlin
import kotlin.math.max
|
|
import kotlin.math.min
|
|
|
|
class Test45 {
|
|
class Solution {
|
|
fun jump(nums: IntArray): Int {
|
|
if (nums.size == 1){
|
|
return 0
|
|
}
|
|
var i = 0
|
|
var jump = 0
|
|
while (i < nums.size -1){
|
|
if (i+nums[i] >= nums.size-1){ // Jump to self's max is enough
|
|
return jump +1
|
|
}
|
|
// Perform next jump
|
|
jump++
|
|
// Find next max
|
|
var maxJumpTo = 0 // Jump score = index+value
|
|
var nextIdx = 0
|
|
for (j in i+1 .. min(i+nums[i],nums.size-1)){
|
|
if (maxJumpTo < j+nums[j]){
|
|
maxJumpTo = j+nums[j]
|
|
nextIdx = j //Jump to idx at j
|
|
}
|
|
}
|
|
i = nextIdx
|
|
}
|
|
return jump
|
|
}
|
|
}
|
|
|
|
fun test(): Unit {
|
|
println(Solution().jump(intArrayOf(2,3,1,1,4)))
|
|
println(Solution().jump(intArrayOf(2,3,0,1,4)))
|
|
println(Solution().jump(intArrayOf(0)))
|
|
println(Solution().jump(intArrayOf(3,4,3,2,5,4,3)))
|
|
println(Solution().jump(intArrayOf(1,2)))
|
|
println(Solution().jump(intArrayOf(1,1,1,1)))
|
|
|
|
}
|
|
} |