Java Sliding Window solution


  • 0

    This is the solution based on idea of sliding window. After reading popular answers to this problem, I found myself too young too simple, sometimes naive.. Not a very concise solution.

    public int findMaxConsecutiveOnes(int[] nums) {
            int n = nums.length;
            if(n < 1) return 0;
            int i = 0, j = 0, res = Integer.MIN_VALUE;
            while(i < n && j < n){
                while(i < n && nums[i] != 1){
                    i ++;
                }
                if(i == n) return res == Integer.MIN_VALUE ? 0 : res;
                j = i + 1;
                while(j < n && nums[j] == 1){
                    j ++;
                }
                res = Math.max(res, j - i);
                i = j + 1;
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.