Это код, который я написал для поиска подмассива максимальной суммы с использованием алгоритма Кадане.
Код:
#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