Chef and new Recepie Time Limit Exceeded

I did this question by finding the minimum frequency element in the array , then add all the elements’s frequencies including the minimum frequency one, then add 2 to it . coz v have to take 2 from the minimum element , then subtract the minimum frequency element’s frequency from it and print it

How do i reduce the time for my code ?

import java.io.*;
import java.util.*;
class CHEFRP 
{

public static void main(String[] args)throws IOException{
    
    int TESTCASES;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    TESTCASES=Integer.parseInt(br.readLine());
    int b=2*TESTCASES,i=0,m,l;
    int a;
    String[] lines=new String[b];
    int[] N=new int[TESTCASES];
     int[][] Ai =new int[TESTCASES][100001];  
     int[] min=new int[TESTCASES];
     int flag=0,minusonecase=-1;
     int[] sum=new int[TESTCASES];
    for(a=0;a<b;a++)
    { 
        lines[a]=br.readLine();
        if(a%2==0)
        {
            N[a/2]=Integer.parseInt(lines[a]);
        }
        if(a%2!=0)
        {
            StringTokenizer stz=new StringTokenizer(lines[a]);
            for(l=0;l<100001;l++)
            {
            if(stz.countTokens()!=0) 
            {
                    Ai[((a-1)/2)][l]=Integer.parseInt(stz.nextToken());  
            }
         else{
             
             break;
         }
        }
        
    }
    
    }
        
        
 
       
    
   
    for(a=0;a<TESTCASES;a++)
    {
        min[a]=Ai[a][0];
        
        for(l=0;l<N[a];l++)
          {
                    if(min[a]>Ai[a][l])
                    {
                        min[a]=Ai[a][l];
                           
                    }
                sum[a]=sum[a]+Ai[a][l];
             
        }
        sum[a]=sum[a]+2-min[a];
    }
    
       for(a=0;a<TESTCASES;a++)
             {
                 for(l=0;l<N[a];l++)
                 {
                     if(Ai[a][l]==1)
                     {  
                        System.out.println(minusonecase);
                        flag=1;
                        break;
                        
                     }
                     
                 }
                 if(flag==1)
                 {
                     flag=0;
                     continue;
                 }
                 System.out.println(sum[a]);
             }
}
}
1 Like

Hi! In this you should tell your computer to calculate simple program i mean reduce your program.
happy programming

1 Like

What do u mean vipin123?

You should reduce the time of finding the minimum frequency element and moreover why you are using such complicated 2d array implementation. Never try to make a 2d array unless and until it is required. You may have look at my code for clearing your doubts.Hope this helps. http://www.codechef.com/viewsolution/6949727

1 Like