Actually the question is like Continuous Subarray sum, but now the array becomes a circular array!!
Here is a great explanation: http://www.geeksforgeeks.org/maximum-contiguous-circular-sum/
So there are two possible answers to the question:
1st, the maxSum subarray is a non-wrapping array, like {-10, 2, -1, 5}, we can find our answer by using continuous subarray sum
2nd, the maxSum subarray is a wrapping array, like{12, -5, 4, -8, 11}. In this case, it means the subarray which we don’t want(not the maxSum subarray) is a non-wrapping array, therefore we can try to find its index, then get what we want from it. But how? Firstly, we reverse all elements in original array, {-12, 5, -4, 8, -11} by using continuous subarray sum method we can find current maxSum array, which equals to the array we don’t want in original one( {-5,4,-8} ). Then we can modify it’s index to satisfy the question’s requirement.
How to judge between 1st case and 2nd one?
We have sum which accumulate all elements in original array, and sum1 which find maxSum within *non-wrapping array, what’s more, sum2 indicates maxSum within reversed array. Therefore, if
Note: above analysis works only in array who is not a all negative array, or it fails.
So, what if the array is a all negative array like {-4,-100, -5,-8} ? In this case, the maxSum is the 1nd case. Thus, we need a bool value isAllNegative to choose our answer!
Here is my code!
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
*/
int continuousSubarraySum(vector<int>& A, vector<int>& res) {
// Write your code here
if(A.empty()) return 0;
int maxSum = INT_MIN, sum = 0, start = 0;
for(int i = 0; i<A.size(); ++i){
sum += A[i];
if(sum > maxSum){
maxSum = sum;
res[0] = start;
res[1] = i;
}
if(sum<0) {
start = i+1;
sum = 0;
}
}
return maxSum;
}
vector<int> continuousSubarraySumII(vector<int>& A) {
// Write your code here
vector<int> res1(2,-1);
vector<int> res2(2,-1);
vector<int> B(A.size(),0);
bool isAllNegative = true;
for(int i = 0; i<A.size(); ++i){
if(A[i] >= 0) isAllNegative = false;
B[i] = -1 * A[i];
}
int sum1 = continuousSubarraySum(A, res1);
int sum = accumulate(A.begin(), A.end(), 0);
int sum2 = continuousSubarraySum(B, res2);
// following code adjust output to satisfy the question's requirement!
int tmp = res2[0];
res2[0] = res2[1]+1;
res2[1] = tmp -1;
if( isAllNegative) return res1;
else return (sum1 >= sum+sum2) ? res1 : res2;
}
};