-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkadane.cpp
More file actions
46 lines (36 loc) · 676 Bytes
/
kadane.cpp
File metadata and controls
46 lines (36 loc) · 676 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int maxSubArray(vector<int>& nums) {
if(nums.empty()) {
return 0;
}
int n = nums.size();
int cs = nums[0];
int ms = nums[0];
int start = 0;
int end = 0;
for(int i = 1; i < n; ++i) {
if(cs <= 0) {
cs = 0;
start = i;
}
cs += nums[i];
if(cs > ms) {
end = i;
ms = cs;
}
}
// start and end represents the range
for(int i = start; i <= end; ++i) {
cout << nums[i] << ' ';
}
cout << '\n';
return ms;
}
int main() {
vector<int> vec{-2, -3, 4, -1, -2, 1, 5, -3};
cout << maxSubArray(vec) << '\n';
return 0;
}