what if all the elements of the array are negitive ?? how does it work then??
Will this work when
Hi Akshay, please mention the link of the corresponding code/question. Thanks.
Hey Akshay, you need to do some modifications for the case when all the elements of the array are negative.
Add maxSum = INT_MIN and re-order the maxSum computation before the currentSum reset to 0.
#include<iostream>
#include<climits>
using namespace std;
int main() {
int TC = 0;
cin >> TC;
for (int idx =0 ; idx < TC; idx ++){
long long int N;
cin>> N;
long long int currSum = 0;
long long int maxSum = INT_MIN;// instead of setting to 0
long long int temp;
//maxSum = 0;
//currSum = 0;
for (int idxj = 1; idxj <= N; idxj++ ) {
cin >> temp;
currSum += temp;
maxSum = max(currSum, maxSum); // maxSum is updated here
if (currSum < 0)
currSum = 0;
}
cout <<maxSum<<endl;
}
return 0;
}
1 Like