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--。

  • 相关阅读:
    docker映射端口无法访问
    Tomcat日志分析
    linux服务器性能测试
    mysql库表结构对比工具
    网络基础知识,不懂看这里
    Python之redis、mysql进程守护
    linux文件查找工具
    nginx解决跨域问题
    redis插入单个较大的键值
    linux系统安全巡检脚本
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13474325.html
Copyright © 2011-2022 走看看