Share my java solution, not the best solution but concise and easy to understand


  • 0
    S
    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int n = nums.length;
            // count of 1 from left to right
            int[] lr = new int[n];
            // count of 1 from right to left
            int[] rl = new int[n];
            for (int i = 1; i < n; i++) {
                lr[i] = nums[i - 1] == 1 ? lr[i - 1] + 1 : 0;
            }
            for (int i = n - 2; i >= 0; i--) {
                rl[i] = nums[i + 1] == 1 ? rl[i + 1] + 1 : 0;
            }
            int max = 0;
            for (int i = 0; i < n; i++) {
                max = Math.max(max, lr[i] + rl[i] + 1);
            }
            return max;
        }
    }
    

Log in to reply
 

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