Minimum Spring Hops
JAVA Code:
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n,m,w=0,g=0,flag=0;
n=s.nextInt();
m=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
for(int i=0;i<n;i++)
{
if(a[i]==m)
{
if(i+a[i]<=n)
w=i;
}
}
for(int i=w+a[w];i<n;i+=a[i])
{
if(i!=n-1)
{
if(i+a[i]>=n)
{
System.out.print(-1);
flag=1;
}
else
g++;
}
else
g++;
}
if(flag==0)
System.out.print(g);
}
}
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n,m,w=0,g=0,flag=0;
n=s.nextInt();
m=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
for(int i=0;i<n;i++)
{
if(a[i]==m)
{
if(i+a[i]<=n)
w=i;
}
}
for(int i=w+a[w];i<n;i+=a[i])
{
if(i!=n-1)
{
if(i+a[i]>=n)
{
System.out.print(-1);
flag=1;
}
else
g++;
}
else
g++;
}
if(flag==0)
System.out.print(g);
}
}
Comments
Post a Comment