File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// kadane algo says that we will carry a sum until it gives the positive sum
2+
class Solution {
3+
public:
4+
int maxSubArray(vector<int>& nums) {
5+
int sum=0;
6+
int maxi=INT_MIN;
7+
for (auto i:nums)
8+
{
9+
sum+=i;
10+
maxi=max(maxi,sum); // everytime take maximum after adding the next element
11+
if (sum<0) sum=0; // whenever sum become less then 0 set its value to zero
12+
}
13+
return maxi;
14+
}
15+
};
16+
// tc sc =O(n), O(1)

0 commit comments

Comments
 (0)