Maximum alternating slice in an array 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&lt;a.length){
        if((a[compareInd]&gt;=0 &amp;&amp; a[i]&lt;=0)||(a[compareInd]&lt;=0 &amp;&amp; a[i]&gt;=0)){
            compareInd=i;
            endInd++;
            i++;
        }else{
            cur_max_size = endInd-startInd+1;
            if(max_size_so_far&lt;cur_max_size){
                max_size_so_far = cur_max_size;
            }
            startInd = i;
            compareInd=startInd;
            endInd=startInd;
            i=startInd+1;
        }
    }
    return max_size_so_far;
}
Hmm. I'm not sure about faster, but you can shorten your code by about 6 lines by doing things a little more efficiently.

First, I'd move your two initializations at the top to be below your if statement. That if statement short-circuits the whole function (which is fine), but since the statement doesn't use those two variables, we shouldn't instantiate them unless it fails to return: that's more efficient. I would also return a.length rather than 1 (to eliminate a 'magic number').

Next, you can eliminate the cur_max_size variable and its usage. Remove the declaration, then take the whole block involving cur_max_size and max_size_so_far and replace with this:

max_size_so_far = Math.max(endInd - startInd + 1, max_size_so_far);


Next, there are two places where you can use i++ inside of another statement, rather than having it stand on its own. i++ means "increment after the original value is used" so this is safe:


Inside of your if conditional (inside the while), delete i++; and change the first statement to be compareInd = i++;
Inside of your else statement, remove i = startInd + 1; and change the startInd=i; line to be startInd = i++;. (Yes, the logic works out.)