这是我为使用 Kadane 算法查找最大和子数组而编写的代码。
代码:
#include <stdio.h>
int maxSum(int a[],int size)
{
int ans=0; //stores the final sum
int sum=0; //stores the sum of the elements in the empty array
int i;
for(i=0;i<size;i++)
{
sum=sum+a[i];
if(sum<0)
{
sum=0;
}
if(ans<sum)
{
ans=sum;
}
}
return ans;
}
void main(){
int j,size,t,total; //size=size of the array,t=number of test cases
scanf("%d\n",&t);
while(t-->0)
{
int a[size];
for(j=0;j<size;j++)
{
scanf("%d ",&a[j]);
}
total=maxSum(a,size);
printf("\n%d",total);
}
}
我一直得到错误的输出:
对于输入:
2 //test cases
3 //case 1
1 2 3
4 //case 2
-1 -2 -3 -4
你的输出是:
0 //it should be 6
0 //it should be -1
最佳答案
唯一的错误是在使用 size
定义数组 a
的大小之前您没有初始化它 - 否则程序没问题。
MAJOR--> 看来您是在 Turbo 上编写代码(因为您使用的是 void main()
而不是 int main(void)
) 这是一个过时的编译器 - 转移到 GCC 或 CLANG。
关于c - 为什么我的 Kadane 算法代码在所有情况下都给出 0 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52442784/