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;
      }
    }
  • 相关阅读:
    春招已近,这份GitHub万星的ML算法面试大全请收下
    [资源推荐] 必须收藏的两个查找论文和代码实现的网站!
    windows下安装pycocotools,亲测有效!
    GAN原理
    2018-07-02
    虚函数和纯虚函数
    友元
    string字符串
    实参和形参
    C/C++学习笔记汇总
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12340532.html
Copyright © 2011-2022 走看看