• + 0 comments

    Python3 solution

    # Enter your code here. Read input from STDIN. Print output to STDOUT
    def longest_segment(A, L):
        n = len(A)
        C = [None] * (n + 1)
        M = [None] * (n + 1)
        M[0] = C[0] = x = y = 0
        for i in range(1, n + 1):
            C[i] = C[i - 1] + A[i - 1]
            if C[i - 1] < C[M[i - 1]]:
                M[i] = i - 1
            else:
                M[i] = M[i - 1]
            k = i - y + x - 1
            while k > 0:
                if C[i] - C[M[k]] >= L:
                    k = M[k]
                else:
                    break
                x, y = k + 1, i
        return 0 if y == 0 else y - x + 1
    
    def max_prefix(s):
        m, t = 0, 0
        for v in s:
            t += v
            m = max(m, t)
        return m
    
    def numeric(s): return list(map(lambda x: 3 if x == '1' else -2, s))
    
    def solve(k, s):
        n = len(s)
        s = numeric(s)
        d = sum(s)
        if d >= 0: return k * n
        d = -d
        mh = max_prefix(s)
        mt = max_prefix(reversed(s))
        r = longest_segment(s, 0)
        if k > 1:
            mult = min((mh + mt) // d, k - 2)
            r = max(r, mult * n + longest_segment(s * 2, mult * d))
        return r
        
    k, s = input().split()
    print(solve(int(k), s))