Improve time from 2 to 1 second

Viewed 35

Question - HackEarth Question [No direct link available so after link click cyclic shift]

Explanation -:

Sample Input -

2

5 2

10101

6 2

010101

Sample Output -

9

3

Explanation-:

For the 1st test case, the value of B(highest value by cyclic shifting strings) is 11010.

After performing 4 cyclic shifts the value represented by array A becomes equal to B for the first time. After performing additional 5 cyclic shifts the value represented by array A becomes B for the second time(2 is the input in second line where 5 in second line is length of string). Hence, the answer is 4 + 5(number of shifts) = 9.

My Code -:

import java.util.*;
class TestClass 
{
    public static void main(String args[] ) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        final int test_cases = sc.nextInt();
        sc.nextLine();
        for(int i = 0;i<test_cases;i++)
        {
            String str = sc.nextLine();
            int b = str.indexOf(" ");
            int a = Integer.valueOf(str.substring(0,b));//split string to 2 integers
            b = Integer.valueOf(str.substring(b+1));
            String st = sc.nextLine(),perm = st;
            for(int j = 0;j<a-1;j++)
            {
                String temp = st.substring(j+1)+st.substring(0,j+1);//cyclic shift
                if(temp.compareTo(perm)>0)
                    perm = temp;
            }
            int j = 1,counter = 0,sum = 0;
            while(counter<b)
            {
                String temp = st.substring(j)+st.substring(0,j);//cyclic shift
                if(temp.equals(perm))
                {
                    sum+=j;
                    counter++;
                    j=1;//now start from 1
                    st = temp;//cyclic shift on string-temp
                }
                j++;
                if(j>a)
                    {
                        break;
                    }
            }
            System.out.println(sum);
        }
    }
}
1 Answers

If you remember all of the shifts that can produce the max result when finding the max result, you can do the second part a lot faster.

Related