Why does my Kadane's algorithm code give an output of 0 for all cases?

  • A+

This is the code I wrote for finding the maximum sum subarray using Kadane's algorithm.


#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);             }         } 

I keep getting the wrong output:

For Input:

2 //test cases   3 //case 1   1 2 3   4 //case 2   -1 -2 -3 -4   

Your Output is:

0 //it should be 6   0 //it should be -1   


The only error is you haven't initialized size before using it to define the size of the array a - otherwise program is fine.

MAJOR--> It seems you are coding it on Turbo (as you have used void main() rather than int main(void)) which is an outdated compiler - shift to GCC or CLANG.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: