Continuous Subarray Sum II
Description:
Given an integer array, find a continuous rotate 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. The answer can be rorate array or non- rorate array)
Example
Give [3, 1, -100, -3, 4], return [4,1].
Solution:
max ( MAX { A }, Total + MAX { -A } )
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> continuousSubarraySumII(vector<int>& A) {
int sz = (int)A.size();
if (sz == 0) return vector<int>();
int maximum = A[0];
int pos = 0;
for (int i = 1; i < sz; ++i) {
if (maximum < A[i]) {
maximum = A[i];
pos = i;
}
}
if (maximum <= 0) return vector<int>({pos, pos});
int pre1 = 0;
int pre2 = 0;
int sum1 = 0;
int sum2 = 0;
int max1 = 0;
int max2 = 0;
int l1 = 0;
int l2 = 0;
int r1 = 0;
int r2 = 0;
int total = 0;
for (int i = 0; i < sz; ++i) {
total += A[i];
sum1 += A[i];
sum2 -= A[i];
if (sum1 <= 0) {
sum1 = 0;
pre1 = i+1;
} else if (sum1 > max1) {
max1 = sum1;
l1 = pre1;
r1 = i;
}
if (sum2 <= 0) {
sum2 = 0;
pre2 = i+1;
} else if (sum2 > max2) {
max2 = sum2;
l2 = pre2;
r2 = i;
}
}
return total + max2 <= max1 ? vector<int>({l1, r1})
: vector<int>({r2+1, l2-1});
}
};