forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontinuous-subarray-sum(AC).cpp
More file actions
49 lines (47 loc) · 1.09 KB
/
continuous-subarray-sum(AC).cpp
File metadata and controls
49 lines (47 loc) · 1.09 KB
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
47
48
49
class Solution {
public:
/**
* @param A an integer array
* @return A list of integers includes the index of
* the first number and the index of the last number
*/
vector<int> continuousSubarraySum(vector<int>& A) {
int n = A.size();
int ll;
int sum;
int msum;
ll = 0;
msum = A[0];
int i;
for (i = 1; i < n; ++i) {
if (A[i] > msum) {
msum = A[i];
ll = i;
}
}
vector<int> ans;
if (msum <= 0) {
ans.push_back(ll);
ans.push_back(ll);
return ans;
}
int mll, mrr;
ll = 0;
msum = sum = 0;
for (i = 0; i < n; ++i) {
sum += A[i];
if (sum < 0) {
sum = 0;
ll = i + 1;
}
if (sum > msum) {
msum = sum;
mll = ll;
mrr = i;
}
}
ans.push_back(mll);
ans.push_back(mrr);
return ans;
}
};