Maximum subarray sum problem maximum subarray sum problem

i am using kadanes algo which is the best optimised approach i learn in the lectures unusual error comes i dont understand how i get the rid of my mistake pls help me in this question

hey @dipeshgupta197 initilize ms = A[0] it will run for all the case weather positive or negative

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

https://ide.codingblocks.com/s/625184 is this is fine i made again in other way

but yet it is not running on hackerblocks does nt pass the test cases

hey @dipeshgupta197 please see this code here you are taking input in wrong format


your implementation part is correct

you write t-- why we may write t>0 also we have to specify terminating condition
or we use unsigned int t i guess

yes i am looking for the same didn’t understand why it is given wrong answer

#include
using namespace std;
int main()
{
int n;
cin>>n;
int arr[1000];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int ms=arr[0];
int cs=0;
for(int i=1;i<n;i++)
{
cs=cs+arr[i];
ms=max(cs,ms);
}
cout<<ms<<endl;
return 0;
}
in this way u said ms=a[0] why sir jabb mein i=0 se start karunga tooo current sum mein mere a[0] negative hoo ya positive voo tooo include hooraha hein

yes yes and dont initilize arr size instead take arr[n].

one more condition if(cs<0) then cs=0;

i ask kya zarrurat hein ki maximum sum ko a[0] se initialize karru sir

yes but in case all element are negative it will give ms as 0 if you initilize ms = 0 in begining

#include
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int ms=arr[0];
int cs=0;
for(int i=0;i<n;i++)
{
cs=cs+arr[i];
if(cs<0)
cs=0;
ms=max(cs,ms);
}
cout<<ms<<endl;
return 0;
}
i understand aapne bolla sarrein element negative hoo too maximum sum zero hooga
cs=0 bhi intialize karraha huin aur maximum of cs and ms leraha huin aaesa bhi too hoosakta hein ki a[0] prr zada negative vala no ho aur kisi aur a[i] prr kamm negative tabb and if valli condition cs=kabhi negative nhi banne deggi

I GUESS MORE BETTER APPROACH TO INCLUDE ALL THE CASES IS WHETHER ALL ELEMENTS ARE NEGATIVE OR POSITIVE OR BOTH IS THE PREVIOUS U CORRECTED THE INPUT FORMAT WHERE WE TAKE MAX_SO_FAR=INT_MIN;