zoukankan      html  css  js  c++  java
  • 1004. Max Consecutive Ones III

    Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

    Return the length of the longest (contiguous) subarray that contains only 1s. 

    Example 1:

    Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
    Output: 6
    Explanation: 
    [1,1,1,0,0,1,1,1,1,1,1]
    Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

    Example 2:

    Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
    Output: 10
    Explanation: 
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
    Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.
    

    Note:

    1. 1 <= A.length <= 20000
    2. 0 <= K <= A.length
    3. A[i] is 0 or 1 
    class Solution {
        public int longestOnes(int[] arr, int k) {
            int res = 0, start = 0;
            int ocount = 0;
            
            for(int end = 0; end < arr.length; end++) {
                if(arr[end] == 1) ocount++;
                while(end - start + 1 - ocount > k) {
                    if(arr[start] == 1) ocount--;
                    start++;                
                }
                res = Math.max(res, end - start + 1);
            }
            return res;
        }
    }

    这题也是sliding window,是上面那道题的简化版,window维护啥呢?维护在k次改变下能生成的最长1子串。上个题有26个字母,这个只有0和1,而且要求要是1子串

    开始,如果当前数字==1,onecount++,如果当前window包不住了,就要start++,注意啊如果arr【start】==1了菜肴onecount--。

  • 相关阅读:
    Spring ListFactoryBean实例
    Spring集合 (List,Set,Map,Properties) 实例
    Spring Bean作用域实例
    Spring内部bean实例
    Spring bean加载多个配置文件
    如何注入值到Spring bean属性
    Spring Bean引用例子
    Spring构造方法注入类型歧义
    Spring JavaConfig @Import实例
    Spring JavaConfig实例
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13474325.html
Copyright © 2011-2022 走看看