zoukankan      html  css  js  c++  java
  • [Algo] 625. Longest subarray contains only 1s

    Given an array of integers that contains only 0s and 1s and a positive integer k, you can flip at most k 0s to 1s, return the longest subarray that contains only integer 1 after flipping.

    Assumptions:

    1. Length of given array is between [1, 20000].

    2. The given array only contains 1s and 0s.

    3. 0 <= k <= length of given array.

    Example 1:

    Input: array = [1,1,0,0,1,1,1,0,0,0], k = 2

    Output: 7

    Explanation: flip 0s at index 2 and 3, then the array becomes [1,1,1,1,1,1,1,0,0,0], so that the length of longest subarray that contains only integer 1 is 7.

    Example 2:

    Input: array = [1,1,0,0,1,1,1,0,0,0], k = 0

    Output: 3

    Explanation: k is 0 so you can not flip any 0 to 1, then the length of longest subarray that contains only integer 1 is 3.

    public class Solution {
      public int longestConsecutiveOnes(int[] nums, int k) {
        // Write your solution here
        int i = 0;
        int start = 0;
        int count = 0;
        int result = 0;
        while (i < nums.length) {
          if (nums[i] == 0) {
            count += 1;
          }
          while (count > k) {
            if (nums[start] == 0) {
              count -= 1;
            }
            start += 1;
          }
          i += 1;
          result = Math.max(result, i - start);
        }
        return result;
      }
    }
  • 相关阅读:
    VS2010安装笔记
    Blend4中文版中截取图片的方法
    改变窗口的位置 (转载)
    窗口的位置
    windows消息大全
    WM_MOUSELEAVE和WM_MOUSEHOVER使用
    setwindowpos
    无注册表的COM调用
    WM_CLOSE WM_QUIT WM_DESTROY 三者的区别
    WM_MOUSEWHEEL消息
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12340532.html
Copyright © 2011-2022 走看看