Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d531d3c

Browse files
authored
Create 41 maximum subarray.cpp
1 parent e05f11e commit d531d3c

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

‎Array/Problems/41 maximum subarray.cpp

Lines changed: 16 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /