My issue
Help me with this problem. How can i optimize it more. It is partially correct.
My code
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class JUMPEND {
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int N = sc.nextInt();
long A[] = new long[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextLong();
}
int counter = 0; // count number of jumps
int index = 0; // keep track of indexs of array
int o = Jump(A, N, counter, index);
if (o==-1 && index==0) {
System.out.println(-1);
}
}
}
public static int Jump(long A[], int N, int counter, int index) {
int j = -2;
if (index == N-1) { // we land on the last element
System.out.println(counter);
return 0;
}
if (A[index] == 0) { // encounter a zero do nothing
return -1;
}
for (int i = 1; i <= A[index]; i++) { // iterates over number of steps a pawns can jump from a element
j = Jump(A, N, counter+1, index+i);
if (i==A[index] && index==0 && j==-1) {// after all iteration we come back to the first element
return -1;
}
if (j >= 0) { // we found the no. of steps
break;
}else if(j==-1 && A[index]==i){
return -1;
}
else if(j==-1){ // encounterd a zero increase i i.e steps
continue;
}
}
return 0;
}
}
Problem Link: CodeChef: Practical coding for everyone