ALGORITHM
-
kadane's algorithm + count == stack stimulation
initlize variables
mxSum = minimum possible value , as numbers can be all negative
mxCt = max count, our answer
sum = running sum
ct = running count
-
ALGO BEGINS HERE
start traversing form the begning of the array
if our current sum is less then zero
- set currSum = currentElement
- count as 1 (as we are count this current element)
else
- add current element to the sum
- increase the count
if our currSum is greater then or equal to currentGlobalMaxSum
if currSum > currentGlobalMaxSum then
set mxCt to currCount
else
set mxCt to maximum of ( mxCt and currCount )
set currentGlobalMaxSum to currSum
print the answers
C++ CODE begins here
int32_t main()
{
vector<int64_t> tc1 = {15,-100,-20,10,5,-100,5,5,5,-10000};
vector<int64_t> tc2 = {-100,5,5,5,5,-10000,50000};
vector<int64_t> tc3 = {-8,-2,-4,-6,-1,-8,-9,-2,-3,-4};
vector<int64_t> a = tc1;
int64_t mxSum = LONG_MIN , mxCt = 0 , sum = 0 , ct = 0;
for(auto i : a)
{
if(sum < 0)
sum = i,
ct = 1;
else
sum += i,
ct++;
if(sum >= mxSum)
{
mxCt = (sum > mxSum) ? ct : max(ct , mxCt);
mxSum = sum;
}
}
cout<<"Max Sum is "<<mxSum<<" "<<"Max len is "<<mxCt;
}
INPUT-TC1
15 -100 -20 10 5 -100 5 5 5 -10000
OUTPUT-TC1
Max Sum is 15 Max len is 3
INPUT-TC2
-100 5 5 5 5 -10000 50000
OUTPUT-TC2
Max Sum is 50000 Max len is 1
INPUT-TC3
-8 -2 -4 -6 -1 -8 -9 -2 -3 -4
OUTPUT-TC3
Max Sum is -1 Max len is 1
- do let me know if its wrong, special case handling, or can be improved