为什么其中一个代码在CodeChef上不起作用?
问题描述
n integers的数组 a :a 1 ,a 2 ,... , n 。您需要在数组中找到最长的连续子阵列,以使该子阵列中的每个整数都是整数,并输出其长度。连续的子阵列是a i 的形式,a
i+1 ,...,a j ,对于某些 i < /em>和 j 。
当我手动提供输入时,下面指定的代码是给出所需输出的测试用例正在通过
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int j = 0;
while(t-- > 0)
{
int n = sc.nextInt();
int count = 0;
int[] arr = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for(int k = 1; k < n; k++)
{
j = k-1;
if(arr[j]%2==0 && arr[k]%2==0)
{
count++;
}
else
{
j++;
}
}
System.out.println(count+1);
}
return;
}
输入:
3
4
1 2 2 4
3
2 4 6
5
2 3 2 2 5
输出:
3
3
2
上述代码为我提供以上正确的答案,当我在其他IDE上运行它
现在以下给定代码适用于 codechef ,它通过所有测试用例
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t-->0)
{
int n=sc.nextInt();
int count = 0;
int res = -1 ;
int[] a=new int[n];
for (int i = 0; i < n; i++)
{
a[i]=sc.nextInt();
}
for (int i = 0; i < n; i++)
{
if (a[i]%2==0)
{
count++;
res = Math.max(count ,res);
}
else {
count = 0;
}
}
System.out.println(res);
}
} catch(Exception e) {
}
}
您能告诉我第一个代码的问题是什么,为什么它在CodeChef上不起作用?
Here is the problem statement: https://www.codechef.com/DAY4DA002/problems/CHEFSUB
Problem description
You are given an array A of N integers: A1, A2, ..., AN. You need to find a longest contiguous subarray in the array such that each integer in this subarray is an even integer, and output its length. A contiguous subarray is of the form Ai, Ai+1, ..., Aj, for some i and j.
The code specified below is giving the desired output when i provide input manually but on CodeChef none of the test cases are getting passed
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int j = 0;
while(t-- > 0)
{
int n = sc.nextInt();
int count = 0;
int[] arr = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for(int k = 1; k < n; k++)
{
j = k-1;
if(arr[j]%2==0 && arr[k]%2==0)
{
count++;
}
else
{
j++;
}
}
System.out.println(count+1);
}
return;
}
Input:
3
4
1 2 2 4
3
2 4 6
5
2 3 2 2 5
Output:
3
3
2
The above code is providing me the above correct answers when I run it on other IDEs
Now the below given code works for CodeChef and it passes all the test cases
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t-->0)
{
int n=sc.nextInt();
int count = 0;
int res = -1 ;
int[] a=new int[n];
for (int i = 0; i < n; i++)
{
a[i]=sc.nextInt();
}
for (int i = 0; i < n; i++)
{
if (a[i]%2==0)
{
count++;
res = Math.max(count ,res);
}
else {
count = 0;
}
}
System.out.println(res);
}
} catch(Exception e) {
}
}
Can you tell me what is the issue with first code and why it is not working on CodeChef?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论