Help needed in dp problem
Anonymous User
266

hello leetcode community,
One of my OA it was given a dp problem like that
there are N elements in an array range from 1 to N, and from a given index we can jump either i-arr[i] or i+arr[i] and we have to reach the last index , for each jump it cost 1 unit.
and we have to find for each index the minimum number of jump to reach the last index , if it is not possible then print -1
let me give an example to clear the problem statement
let arr[]={1,3,1,3,4}
from index 1 we can jump to index 2 and then again we can go to index 5 so total jump required is two
for index two it can reach at index N through i jump so tatal jump required is 1
and for third index we can first jump to index 2 and from index 2 we can reach index 5 directly, so minimum jump is 2
same for 4th index it will take jump 3
and for last index it doesn't require any jump because it is already present in last index so for last index ans will be zero
so overall output will be [2,1,2,3,0]
constraint
2<=N<=100000;
1<=arr[i]<=N;
Input
4
3 4 2 1
output
1 -1 2 0

My solution was giving correct result for both sample inputs but it was not accepted in the online judge
can anyone share code /approach for this question, it will be really helpful
sorry for my poor english :(

Comments (5)
No comments yet.