【发布时间】:2019-10-13 23:18:15
【问题描述】:
这是来自极客的问题陈述(链接:https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0)
根据编译和测试选项,我的代码运行良好。但是当我尝试提交时,它会抛出多个测试用例失败的错误。
谁能帮我解决这个问题?
代码:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Kadane
{
public static void main(String[]args) throws IOException,NumberFormatException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of test cases");
int T = Integer.parseInt(br.readLine());
for(int t=0 ; t<T ; t++)
{
int N,a=0;
int sum1=0,maxsum=-2147483648,kadanesum=-2147483648;
System.out.println("Enter the size of array : ");
N = Integer.parseInt(br.readLine());
int arr[] = new int[N];
System.out.println("Enter the array elements separated by space");
String S = new String(br.readLine());
String elem[] = S.split(" ");
for(String e:elem)
{
arr[a] = Integer.parseInt(e);
a++;
}
for(int i=0 ; i<N ; i++)
{
for(int j=i ; j<N ; j++)
{
sum1 = sum1 + arr[j];
if(maxsum<sum1)
{
maxsum=sum1;
}
}
if(maxsum>kadanesum)
{
kadanesum=maxsum;
}
sum1=0;
maxsum=-2147483648;
}
System.out.println("\tKadane Sum = " + kadanesum);
}
}
}
我的代码链接:https://ide.geeksforgeeks.org/tXNHh28A0D
我的意见: 5(测试用例数)
3(数组大小)
1 2 3(数组元素)
5
1 2 3 -2 5
10
2 9 3 -10 -20 34 28 -50 30 -1
7
4 5 -10 -50 3 9 8
8
8 9 8 -25 25 1 2
我的输出: 输入测试用例数
输入数组的大小: 输入以空格分隔的数组元素 Kadane Sum = 6
输入数组的大小: 输入以空格分隔的数组元素 Kadane Sum = 9
输入数组的大小: 输入以空格分隔的数组元素 Kadane Sum = 62
输入数组的大小: 输入以空格分隔的数组元素 Kadane Sum = 20
输入数组的大小: 输入以空格分隔的数组元素 Kadane Sum = 28
我在提交代码时收到以下错误消息:
错误的答案。 !!!错误的答案 可能您的代码对于多个测试用例 (TC) 无法正常工作。 您的代码失败的第一个测试用例:
输入:(根据网站) 3 1 2 3
它的正确输出是: 6
我在输入测试用例(测试用例 1)中使用了相同的输入,输出与预期相同。
谁能帮我使用 StringBuffer 优化代码?
【问题讨论】:
-
请将您的代码编辑到问题中(不是作为链接)
-
您好,我已添加代码。
-
@Ajay 编码网站不想要输出,因为你已经给了他们他们大多数时候只想要数字,删除你打印的行
enter the size of the array,Enter the array elements....,它也是在问题陈述中给出了预期的输入和预期的输出。您必须遵循这些标准,否则他们会拒绝您的回答。 -
@rahul,谢谢...它现在被接受了。
标签: java arrays sub-array contiguous kadanes-algorithm