Skip to content

Commit dfcfe26

Browse files
Merge pull request #246 from Kinshu-Learner/main
feat(Cpp): Maximum Sum Subarray problem Kadane's Algorithm
2 parents 4c911e2 + 11d22da commit dfcfe26

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include<iostream>
2+
#include<vector>
3+
#include<climits>
4+
#include<algorithm>
5+
6+
class Solution {
7+
public:
8+
int maxSubArray(std::vector<int>& nums) {
9+
if (nums.empty()) {
10+
return 0;
11+
}
12+
int maxSum = INT_MIN; // Stores the maximum sum found so far
13+
int currSum = 0; // Stores the sum of the current subarray
14+
for(size_t i = 0; i < nums.size(); i++){
15+
currSum += nums[i];
16+
maxSum = std::max(currSum, maxSum);
17+
18+
// If the current sum is negative, it won't contribute to a larger sum,
19+
// so we reset it to 0 to start a new subarray from the next element.
20+
if(currSum < 0){
21+
currSum = 0;
22+
}
23+
}
24+
25+
return maxSum;
26+
}
27+
};
28+
29+
int main() {
30+
Solution sol;
31+
std::vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
32+
33+
int result = sol.maxSubArray(nums);
34+
35+
std::cout << "The maximum subarray sum is: " << result << std::endl;
36+
37+
return 0;
38+
}

0 commit comments

Comments
 (0)