c - 为什么我的 Kadane 算法代码在所有情况下都给出 0 的输出?

标签 c arrays kadanes-algorithm

这是我为使用 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)) 这是一个过时的编译器 - 转移到 GCCCLANG

关于c - 为什么我的 Kadane 算法代码在所有情况下都给出 0 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52442784/

相关文章:

php - 带前导零的整数数组 - 奇怪的结果

java - Java中使用Kadane算法求子数组的最大和

algorithm - kadane算法-输入是否有顺序限制?

java - java中的kadane算法

c - 通过 TCP 发送的文件创建类型为 : application/octet-stream

Core Audio - 远程 IO 困惑

创建的文件中没有任何内容

c - 通过套接字传输数组时遇到问题

c - 如何对同一变量中的所有值求和?

php - 引用 - 这个错误在 PHP 中是什么意思?