CHEALG - Wrong Answer - Help

Why does my code give WA?

Problem: https://www.codechef.com/LTIME79B/problems/CHEALG

public static void main (String[]args) throws java.lang.Exception
  {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt ();
    in.nextLine();
    for (int i = 0; i < t; i++)
      {
        String s = in.nextLine();
        int l = s.length();
        int streak=1;
        int sum=1;
        for (int j=1;j<l;j++)
        {
            if (s.charAt(j)==s.charAt(j-1))
            {
                streak++;
                
            }
            else
            {
                sum++;
                if (streak<10)
                {
                    sum++;
                }
                else if (streak>=10) 
                {
                    sum+=2;
                }
                else if (streak>=100)
                {
                    sum+=3;
                }
                else if (streak>=1000)
                {
                    sum+=4;
                }
                streak=1;
            }
            if (j==l-1)
            {
                if (streak<10)
                {
                    sum++;
                }
                else if (streak>=10) 
                {
                    sum+=2;
                }
                else if (streak>=100)
                {
                    sum+=3;
                }
                else if (streak>=1000)
                {
                    sum+=4;
                }
            }
        }
        
        if (sum<l) System.out.println("YES");
        else System.out.println("NO");
      }
  }

Is it giving wrong answer on every test case??

initiate sum with 0

1 Like

The problem is in the else if conditions.Assume streak is 100.Now what will be the value of sum according to your program. it will make sum+=2 and not sum+=3.
The problem is ,it will check the first else if condition which is (streak>=10) so now if streak is 10 or 100 or 1000 this condition will always be true and sum will always become sum+=2.It will never check 3rd and 4th condition.
So You should make 4 conditions as streak<10, streak<100, streak<1000 and streak>=1000.
Another thing is you have initialised sum=1 make it sum=0.

2 Likes

Thanks for helping!