Reputation: 45
Hi i have solved one coding competition problem in that this and un acceptable solution is this
boolean found=true;
int ar[]=new int[n];
for (int i = 0; i < n; i++) {
//ar[i]=sc.nextInt();
int temp=sc.nextInt();
if(h==temp+x) {
found=false;
System.out.println("Yes");
}
}
if(found) {
System.out.println("NO");
}
and accepted solution is this
for (int i = 0; i < n; i++) {
//ar[i]=sc.nextInt();
int temp=sc.nextInt();
if(h==temp+x) {
found=false;
}
}
if(found) {
System.out.println("NO");
}else{
System.out.println("YES");
}
I did not found any difference in that because in 1st i have assign boolean value and print and second i just assign and later print and just normally made this change and its accepted can any one explain me
Upvotes: 0
Views: 38
Reputation: 86
In the first code, if the condition h==temp+x
matched multiple time then you will print multiple time while in second you are printing one time only. If you want above one to work you can put break condition inside the if.
For eg: temp values are 1,2,3,3,4
and h
is 6
and x
is 3
. You will print yes
twice.
Possible solution:
boolean found=true;
int ar[]=new int[n];
for (int i = 0; i < n; i++) {
//ar[i]=sc.nextInt();
int temp=sc.nextInt();
if(h==temp+x) {
found=false;
System.out.println("Yes");
break;
}
}
if(found) {
System.out.println("NO");
}
By the way putting break
will make your code run faster for some cases.
Upvotes: 1