校招真题练习012 最长全1串(美团)

最长全1串

题目描述
给你一个01字符串,定义答案=该串中最长的连续1的长度,现在你有至多K次机会,每次机会可以将串中的某个0改成1,现在问最大的可能答案

输入描述:
输入第一行两个整数N,K,表示字符串长度和机会次数
第二行输入N个整数,表示该字符串的元素
( 1 <= N <= 300000
, 0 <= K <= N )

输出描述:
输出一行表示答案

 1 def getMax(B:'List[int]'):
 2     n = len(B)
 3     maxlen = 0
 4     curlen = 0
 5     for i in range (n):
 6         if B[i] == 1:
 7             curlen += 1
 8         else:
 9             maxlen = max(maxlen,curlen)
10             curlen = 0
11     return max(maxlen,curlen)
12 
13 def longestOnes(A: 'List[int]', K: int) -> int:
14     if K == 0:
15         return getMax(A)
16     n = len(A)
17     zlist = list()
18     for i in range(n):
19         if A[i] == 0:
20             zlist.append(i)
21     if len(zlist)<=K:
22         return n
23     maxlen = 0
24     for zi in range(len(zlist)-K+1):        
25         ti = zi+K            
26         left = 0
27         right = len(A)-1
28         if zi==0:
29             left = zlist[zi]
30         else:
31             left = zlist[zi-1]+1
32         if zi == len(zlist)-K:
33             right = len(A) - 1
34         else:
35             right = zlist[ti] - 1
36         maxlen = max(maxlen, right - left +1)    
37     return maxlen
38 
39 if __name__ == '__main__':
40     line0 = list(map(int,input().strip().split()))
41     N = line0[0]
42     K = line0[1]
43     ary = list(map(int,input().strip().split()))
44     result = longestOnes(ary,K)
45     print(result)

算法思路:双指针,滑动窗口

转载于:https://www.cnblogs.com/asenyang/p/11100603.html

你可能感兴趣的:(校招真题练习012 最长全1串(美团))