【问题标题】:Why does my Kadane's algorithm code give an output of 0 for all cases?为什么我的 Kadane 的算法代码在所有情况下都给出 0 的输出?
【发布时间】:2018-09-22 03:32:44
【问题描述】:

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

【问题讨论】:

    标签: c arrays kadanes-algorithm


    【解决方案1】:

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

    MAJOR--> 看来您是在 Turbo 上对其进行编码(因为您使用的是 void main() 而不是 int main(void)),这是一个过时的编译器 - shift GCCCLANG

    【讨论】:

    • 不,他显然没有使用 Turbo C,否则int a[size]; 不会编译。
    • @Jabberwocky 我用的不多,我猜是void main()已经用过了。谢谢!
    • 但是我已经在 main() 函数中声明了 size 并将它作为参数传递给 maxSum() 函数。此外,我也尝试使用 int main(),但我一直得到相同的输出。
    • @PallaviSingh 是的,您已经在main 中声明了它,但是您是否对其进行了初始化,我的意思是size 的值是多少?
    • 是的,尺寸必须是用户输入的,我没有为此添加 scanf() 语句。一旦我这样做,它就会运行。
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多