Why my O(1) code is showing tle for the last 3 tasks?
The same code when converted to C++ gives AC>
Problem link: CodeChef: Practical coding for everyone
My Solution:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
long t=sc.nextLong();
while(t>0){
long n=sc.nextLong();
if((n*(n+1)/2)%2!=0){
System.out.println(0);
}
else {
long N = n * (n + 1) / 4;
long count =0;
long i=(long)Math.round(Math.sqrt(n*(n+1)/2));
long a= (i)*(i+1)/2;
//System.out.println(i);
//System.out.println(a);
if(a==N){
count = Math.min(i,n-(i))+i*(i-1)/2 +(n-i)*(n-i-1)/2;
}
else if(a>N){
count = n-(i-1);
}
System.out.println(count);
}
t--;
}
}
}
Hey please help me out with my code I tried to find alternative to reduce time.But Time Limit is exceeding here in my code
import java.util.Scanner;
class Codechef {
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
for(int i=0;i<t;i++) {
int n=scan.nextInt();
count(n);
}
scan.close();
}
public static void count(int n) {
int c=0;
int sum=n*(n+1)/2;
if(sum%2==0) {
int[] a=new int[n];
for(int p=0;p<n;p++) {
a[p]=p+1;
}
for(int j=0;j<n;j++) {
for(int k=j+1;k<n;k++){
int[] b=a.clone();
int temp=b[j];
b[j]=b[k];
b[k]=temp;
int u=0;
for(int w:b) {
u+=w;
if(u==sum/2) {
c+=1;
break ;
}else if(u>sum/2) {
break;
}
}
}
}
}
System.out.println©;
}
}
Hoping someone will surely help.
afmab
September 14, 2020, 10:36am
3
faced similar problem while submitting in java.Here are a few suggestions that might help-
1)Use buffer reader or other fast input method
2)don’t use system.out.print for each case instead store answers in a string and print once after finding answer for all cases outside while
these might help
2 Likes
Yeah I also used the buffered reader but still did not get all test cases passed.
And I didn’t get ur 2nd point
1 Like
Your code is right, Just use Fast I/O whenever you code in JAVA. Fast I/O in Java in Competitive Programming - GeeksforGeeks
1 Like
Yeah that’s where I am stuck how to reduce it
afmab
September 14, 2020, 10:47am
8
what i mean is:
StringBuilder ans=new StringBuilder();
while(t>0){
//solution
ans.append(answer+"\n");
}
System.out.println(ans);
}
this where answer is the answer for that particular case
I did use the Fast I/O still all test cases did not pass.Did it work for u?
Still it wont work I guess
I replied to the one who posted @rahul_th not you.
Okay sorry for misunderstanding
1 Like
Using this with StringBuilder worked for me. Thank you
Thank you so much. I get it now.
You’re using 2 for loops ofc it’ll give the. Try to do it in O(1) time. Logic is given in my code.