Minimum Jumps to End
JavaScript
Hard
6 views
Problem Description
Each element tells max jump length. Find minimum jumps needed to reach last index. If not possible, print -1.
Input Format
One line: n then n integers.
Output Format
One integer jumps.
Official Solution
const fs=require('fs');const p=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!p[0])process.exit(0);let i=0;const n=Number(p[i++]);let arr=new Array(n);for(let j=0;j<n;j++)arr[j]=Number(p[i++]);if(n<=1){process.stdout.write('0');process.exit(0);}let jumps=0;let curEnd=0;let far=0;for(let j=0;j<n-1;j++){far=Math.max(far,j+arr[j]);if(j===curEnd){jumps++;curEnd=far;if(curEnd<=j){process.stdout.write('-1');return;}}}process.stdout.write(String(jumps));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!