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);
    }
}

Comments

Popular posts from this blog

Reverse String Till Underscore

Count of common characters in two strings

RECTANGULAR SUM