1

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

Code:

#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  
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

1 Answers1

4

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.

Gaurav
  • 1,570
  • 5
  • 17
  • 1
    No, he is obviously not using Turbo C, otherwise `int a[size];` would not have compiled. – Jabberwocky Sep 21 '18 at 11:49
  • @Jabberwocky I haven't used it much, I guessed it as `void main()` has been used. Thanks! – Gaurav Sep 21 '18 at 11:56
  • But I have declared size in the main () function and passed it as an argument to the maxSum () function. Moreover, I tried using int main() as well, but I keep getting the same output. – Pallavi Singh Sep 22 '18 at 12:08
  • 1
    @PallaviSingh Yes you have declared it in `main` but have you initialized it, I mean what is the value of `size`? – Gaurav Sep 22 '18 at 12:12
  • Yes, the size has to be user input and I have not added a scanf() statement for that. It'll run once I do that. – Pallavi Singh Sep 23 '18 at 13:13
  • @PallaviSingh If that works then do visit this: https://stackoverflow.com/help/someone-answers – Gaurav Sep 23 '18 at 13:14