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)
Have you met this question in a real interview?
Yes
Example
Give[-3, 1, 3, -3, 4]
, return[1,4]
.
line 13, need to record the range with separate variable name
make sure left , right definition, they change for every element
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
if (A.empty()) {
return vector<int>({-1, -1});
}
int left = 0, right = 0;
int maxleft = 0, maxright = 0;
int maxSum = A[0], sumSofar = A[0];
for (int i = 1; i < A.size(); ++i) {
if (sumSofar >= 0) {
sumSofar += A[i];
} else {
sumSofar = A[i];
left = i;
}
right = i;
if (sumSofar > maxSum) {
maxSum = sumSofar;
maxleft = left;
maxright = right;
}
}
return vector<int>({maxleft, maxright});
}
};