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;
      }
    }
  • 相关阅读:
    2.替换空格
    1.二维数组的查找
    poj 2431 expedition
    python入门第三天
    python入门第二天__练习题
    [Python3.6] print vs sys.stdout.write
    python入门第二天
    使用Flask-mail发送邮件无法连接主机
    KMP
    逆序对 线段树&树状数组 (重制版)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12340532.html
Copyright © 2011-2022 走看看