1

这是我为使用 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  
4

1 回答 1

4

size唯一的错误是您在使用它来定义数组的大小之前没有初始化a- 否则程序很好。

MAJOR-->看来您是在Turbo上对其进行编码(正如您所使用的void main(),而不是int main(void)),这是一个过时的编译器 - 转移到GCCCLANG

于 2018-09-21T11:45:10.737 回答