Over 2 years, I have been finding bugs in other's code but did that improve my coding skills?? So just wanted to try wearing a developer's hat and write my own code for some of questions mostly asked in interviews. Now its your chance to find the bugs in the code written by code inspectors. Take up the Code Inspections Challenge. This is similar to Find the bug series posted earlier on this blog but here code is written by me and I myself am not sure of any bugs in the code here.
Question: You're given an array containing both positive and negative integers and required to find sub-array with largest sum. Code is written is C++.
Question: You're given an array containing both positive and negative integers and required to find sub-array with largest sum. Code is written is C++.
#include <iostream.h>
int greatest_sum(const int* nums, const int count)
{
if(count<=0 || nums==NULL)
{
cout << "Invalid Input\n";
return -1;
}
int total = 0;
int best = 0;
int cnt=0;
int subarr[count];
int p=0;
for(int i = 0; i < count; i++)
{
total += nums[i];
cnt++;
if(total > best)
{
best = total;
for (int j=i-cnt+1,n=0;j<=i;j++,n++)
subarr[n]=nums[j];
p=cnt;
}
else if(total <= 0)
{
total = 0;
cnt=0;
}
}
cout <<"Sub Array:\n";
for (int k=0;k<p;k++)
{
cout << subarr[k];
cout << "\n";
}
return best;
}
int main()
{
int nums[8]={-10,-1,10,-5,7,-8,2,39};
int best=greatest_sum(nums,8);
cout <<"Largest Sum is:";
cout << best;
getchar();
return 0;
}