A bit optimized, removing the array posNegs.
class Solution {
public int maxSubArray(int[] nums)
{
final int size = nums.length;
int max = Integer.MIN_VALUE;
int firstPosIndex = 0;
while (firstPosIndex < size && nums[firstPosIndex] <= 0) {
++firstPosIndex;
}
int lastPosIndex = size; // Exclusive
while (lastPosIndex > firstPosIndex && nums[lastPosIndex - 1] <= 0) {
--lastPosIndex;
}
// Initial max should there be only negative numbers.
if (firstPosIndex >= lastPosIndex) {
for (int i = 0; i < size; ++i) {
int num = nums[i];
if (max < num) {
max = num;
}
}
return max;
}
int sum = 0;
int i = firstPosIndex;
while (i < lastPosIndex) {
// Positive numbers:
while (i < lastPosIndex && nums[i] > 0) {
sum += nums[i];
++i;
}
if (max < sum) {
max = sum;
}
// Negative numbers:
if (i < lastPosIndex) {
sum += nums[i];
++i;
while (i < lastPosIndex && nums[i] <= 0) {
sum += nums[i];
++i;
}
if (sum < 0) {
sum = 0;
}
}
}
return max;
}
}