JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given a binary array nums, return the maximum number of consecutive 1’s in the array if you can flip at most one 0.

Example 1:

Input: nums = [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 4

Constraints:

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.

Code

485

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int res = 0;
        
        int left = 0;
        int right = 0;
        int zeros = 0;

        while (right < nums.length) {
            if (nums[right] == 0) {
                zeros++;
            }

            while (zeros == 2) {
                if (nums[left] == 0) {
                    zeros--;
                }
                
                left++;
            }

            res = Math.max(res, right - left + 1);
            right++;
        }
        
        return res;
    }
}
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int res = 0;
        
        int count = 0;
        for(int num : nums) {
            if(num == 1) {
                count++;
            } else {
                list.add(count);
                res = Math.max(res, count);
                
                count = 0;
                list.add(0);
            }
        }
        
        if(count != 0) {
            res = Math.max(res, count);
            list.add(count);
        }
        
        for(int i = 0; i < list.size(); i++) {
            int curr = list.get(i);
            
            if(curr == 0) {
                int len = 1;
                
                if(i != 0 && list.get(i - 1) != 0){
                    len += list.get(i - 1);
                }
                
                if(i != list.size() - 1 && list.get(i + 1) != 0) {
                    len += list.get(i + 1);
                }
                
                res = Math.max(res, len);
            }
        }
        
        return res;
    }
}