Continuous Subarray Sum

Continuous Subarray Sum

Description:

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone)

Example:

Give [-3, 1, 3, -3, 4], return [1,4].

分析:

Maximum Subarray,只是需要记录起始和结束的下标。

Code:

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
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) {
// Write your code here
vector<int> index;
int max_endding_here = A[0];
int max_so_far = A[0];
int start = 0;
int last_start = 0;
int end = 0;
bool set_i = false;

for (int i = 1;i < A.size();i++) {
max_endding_here = max_endding_here + A[i];
if (max_endding_here < A[i]) {
max_endding_here = A[i];
set_i = true;
}
if (max_so_far <= max_endding_here) {
max_so_far = max_endding_here;
end = i;
last_start = start;
}
if(set_i) {
start = i;
set_i = false;
}
}
if (start > end) {
start = last_start;
}
index.push_back(start);
index.push_back(end);
return index;
}
};