Skip to content

Commit 327aea8

Browse files
Added Kadane's Algorithm with start and end index tracking
1 parent b9c118f commit 327aea8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
/*
5+
Kadane's Algorithm (with index tracking)
6+
Time Complexity: O(n)
7+
*/
8+
9+
pair<int, pair<int, int>> kadane_with_indices(const vector<int>& arr) {
10+
int max_sum = INT_MIN;
11+
int current_sum = 0;
12+
int start = 0, temp_start = 0, end = 0;
13+
14+
for (int i = 0; i < arr.size(); i++) {
15+
current_sum += arr[i];
16+
17+
if (current_sum > max_sum) {
18+
max_sum = current_sum;
19+
start = temp_start;
20+
end = i;
21+
}
22+
23+
if (current_sum < 0) {
24+
current_sum = 0;
25+
temp_start = i + 1;
26+
}
27+
}
28+
return {max_sum, {start, end}};
29+
}
30+
31+
int main() {
32+
vector<int> arr = {-2, -3, 4, -1, -2, 1, 5, -3};
33+
34+
auto result = kadane_with_indices(arr);
35+
cout << "Maximum Subarray Sum: " << result.first << "\n";
36+
cout << "Start Index: " << result.second.first << "\n";
37+
cout << "End Index: " << result.second.second << "\n";
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)