I'm working on the problem:
Given array with positive and negative values, return the maximum alternating slice size; two elements are alternating if they have different signs, zero is treated as both negative and positive.
Time complexity: \$O(N)\$
Space complexity: \$O(1)\$
I developed a working code and would like to know if there is any method to make the code shorter or faster.
public static int maxSizeAlterSlice(int[] a){
int max_size_so_far = -1;
int cur_max_size = -1;
if(a.length == 1)
return 1;
int startInd = 0;
int endInd = 0;
int i=1;
int compareInd=0;
while(i<a.length){
if((a[compareInd]>=0 && a[i]<=0)||(a[compareInd]<=0 && a[i]>=0)){
compareInd=i;
endInd++;
i++;
}else{
cur_max_size = endInd-startInd+1;
if(max_size_so_far<cur_max_size){
max_size_so_far = cur_max_size;
}
startInd = i;
compareInd=startInd;
endInd=startInd;
i=startInd+1;
}
}
return max_size_so_far;
}
-1for the array{-1, 1}with your code ... \$\endgroup\$-1, 0, 1count as an alternating sequence of length 3? \$\endgroup\$1, 0, 1and1, 0, -1both valid alternating sequences? \$\endgroup\$