Problem:


Score : 500 points

Problem Statement

In CODE FESTIVAL XXXX, there are N+1 participants from all over the world, including Takahashi.

Takahashi checked and found that the time gap (defined below) between the local times in his city and the i-th person's city was D_i hours.
The time gap between two cities is defined as follows. For two cities A and B, if the local time in city B is d o'clock at the moment when the local time in city A is 0 o'clock, then the time gap between these two cities is defined to be min(d,24-d) hours.
Here, we are using 24-hour notation.
That is, the local time in the i-th person's city is either d o'clock or 24-d o'clock at the moment when the local time in Takahashi's city is 0 o'clock, for example.

Then, for each pair of two people chosen from the N+1 people, he wrote out the time gap between their cities. Let the smallest time gap among them be s hours.

Find the maximum possible value of s.

Constraints

1 \leq N \leq 50

0 \leq D_i \leq 12

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the maximum possible value of s.

Sample Input 1

3
7 12 8

Sample Output 1

4

For example, consider the situation where it is 7, 12 and 16 o'clock in each person's city at the moment when it is 0 o'clock in Takahashi's city. In this case, the time gap between the second and third persons' cities is 4 hours.

Sample Input 2

2
11 11

Sample Output 2

2

Sample Input 3

1
0

Sample Output 3

0

Note that Takahashi himself is also a participant.



Sample input:
3
7 12 8


Sample output:
4

Submission status: Accepted

Solution code:
import collections
from collections import deque
N=int(input())
D=list(map(int,input().split()))
c=collections.Counter(D)
count0=0
count12=0
zeroflag=0
l=[]
if c[12]>0:
    count12=c[12]
if c[0]>0:
    count0=c[0]+1
#print(l,count0,count12)
#print(n)
allmax=0
q=deque()
l=[]



if (count0==0)and(zeroflag==0):
    q.append([0])
    q.append([24])
elif (count0==1)and(zeroflag==0):
    q.append([0,0])
    q.append([0,24])
    q.append([24,24])
else:
    zeroflag=1

if (count12==1)and(zeroflag==0):
    length=len(q)
    j=0
    while j<length:
        buf1=[]
        l=q.popleft()
        buf1.extend(l)
        l.append(12)
        q.append(l)
        j=j+1
elif count12>1:
    zeroflag=1

if zeroflag==0:
    for i in range(1,12):
        length=len(q)
        j=0
        if c[i]==0: continue
        if c[i]==1:
            while j<length:
                buf1=[]
                buf2=[]
                l=q.popleft()
                buf1.extend(l)
                buf1.append(i)
                buf2.extend(l)
                buf2.append(24-i)
                q.append(buf1)
                q.append(buf2)
                j=j+1
        if c[i]==2:
            while j<length:
                buf1=[]
                buf2=[]
                buf3=[]
                l=q.popleft()
                buf1.extend(l)
                buf1.extend([i,i])
                buf2.extend(l)
                buf2.extend([24-i,24-i])
                buf3.extend(l)
                buf3.extend([i,24-i])
                q.append(buf1)
                q.append(buf2)
                q.append(buf3)
                j=j+1
        if c[i]>2:
            zeroflag=1
            break
        #print(q)

#print(q)

if zeroflag==0:
    for l in q:
        l.sort()
        mi=100
        n=len(l)
        for j in range(n-1):
            mi=min(mi,l[j+1]-l[j],24-l[j+1]+l[j])
        mi=min(mi,l[n-1],24-l[n-1])
    #print(mi)
        allmax=max(allmax,mi)
else:
    allmax=0
print(allmax)

"""
for i in range(pow(2,n)):
    buf=[0]
    bit=[0]*n
    mi=100
    if count12==1:
        buf.append(12)
    buf.append(0)
    for j in range(n):
        if (i>>j)&1:
            bit[j]=1
    #print(bit)
    for j in range(n):
        buf.append(l[j][bit[j]])
    buf.sort()
    buf.append(24)
    #print(buf)
    for j in range(len(buf)-1):
        mi=min(mi,buf[j+1]-buf[j])
    allmax=max(allmax,mi)
print(allmax)
"""

Submission status: Accepted

Solution code:
from itertools import product
from collections import Counter
N=int(input())
D=list(map(int, input().split()))
res=0
c=Counter(D)
if c[0]>0 or max(c.values())>2:print(0);exit()
if N>13:print(1);exit()
for b in product(*((d,24-d) for d in D)):
    d0, m= 0,1<<30
    for d in sorted(b):
        m=min((d-d0),24-(d-d0),m)
        d0=d
    m=min(d0,24-d0,m)
    res = max(res,m)
print(res)

Submission status: Accepted

Solution code:
import math
from typing import List, Counter, Tuple
from collections import Counter
from itertools import permutations


def read_int() -> int:
    return int(input().strip())


def read_ints() -> List[int]:
    return list(map(int, input().strip().split(' ')))


INF = 10**9

def solve() -> int:
    N = read_int()
    D = read_ints()
    if N>23:
        return 0
    D.sort(key=lambda d:min(d, 24-d))
    right = True
    assignment = [False]*24
    assignment[0] = True
    for d in D:
        if right:
            if assignment[d]:
                return 0
            assignment[d] = True
        else:
            if assignment[(24-d)%24]:
                return 0
            assignment[(24-d)%24] = True
        right = not right

    count = 0
    counts = []
    for i in range(1, len(assignment)+1):
        i %= 24
        if not assignment[i]:
            count += 1
        else:
            counts.append(count)
            count = 0
    return min(counts)+1
        


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
from collections import Counter
import marshal
N = int(input())
D = Counter(list(map(int, input().split())))
P = [[0]]
for i in range(13):
    if D.get(i,0) == 0:
        continue
    if D.get(i,0) == 1:
        Q = marshal.loads(marshal.dumps(P))
        for p in P:
            p.append(i)
        for q in Q:
            q.append(24-i)
        P += Q
    if D.get(i,0) == 2:
        for p in P:
            p.append(i)
            p.append(24-i)
    if D.get(i,0) >= 3:
        print(0)
        exit()
res = 0
for p in P:
    m = float("inf")
    for i in range(len(p)):
        for j in range(i+1,len(p)):
            if abs(p[i]-p[j])>12:
                m = min(24-abs(p[i]-p[j]),m)
            else:
                m = min(abs(p[i]-p[j]),m)
    res = max(m,res)
print(res)

Submission status: Accepted

Solution code:
from itertools import product
N = int(input())
D = list(map(int,input().split()))
max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

def solve():
    cnt = [0]*13
    for d in D:
        cnt[d] += 1

    if cnt[0] > 0 or any(c > 2 for c in cnt):
        return 0

    if N > 13:
        return 1

    res = 0
    for p in product(*((d, 24-d) for d in D)):
        p = [0]+sorted(p)
        r = min(b-a for a,b in zip(p,p[1:]))
        r = min2(r, p[0]-p[-1]+24)
        res = max2(res,r)
    return res

print(solve())

Submission status: Accepted

Solution code:
from collections import Counter
from copy import deepcopy


def solve(c_d):
    one = [24]
    all_d = []
    for i in range(13):
        if c_d[i] >= 3:
            return 0
        elif c_d[i] == 2:
            all_d.append(i)
            all_d.append(24 - i)
        elif (i == 0 or i == 12) and c_d[i] == 1:
            all_d.append(i)
        elif c_d[i] == 1:
            one.append(i)
    ans = 0
    for i in range(1 << len(one)):
        now = deepcopy(all_d)
        for j in range(len(one)):
            if (i >> j) & 1:
                now.append(one[j])
            else:
                now.append(24 - one[j])
        now_ans = float("inf")
        for j in range(len(now)):
            for k in range(j + 1, len(now)):
                now_ans = min(now_ans, abs(now[j] - now[k]))
        ans = max(ans, now_ans)
    return min(ans, 24 - ans)


def main():
    n = int(input())
    d = list(map(int, input().split()))
    d.append(0)
    print(solve(Counter(d)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

N = int(input())
D = list(map(int, input().split()))

if 0 in D:
    print(0)
    exit()

counter = defaultdict(int)
for d in D:
    counter[d] += 1

for k in counter:
    if counter[k] >= 3:
        print(0)
        exit()

# 解を求める
ans = 0
for b in range(2 ** 13):
    tmp = [0] # 高橋くんがいる
    for key in range(13):
        if counter[key] == 2:
            tmp += [key, 24 - key]  # 両方
        elif counter[key] == 1:
            # 左右どちらかを試す (b次第)
            if b & 1:
                tmp += [key]
            else:
                tmp += [24 - key]
        b = b >> 1
    
    # gapの計算
    gap = 12
    for i in range(len(tmp)):
        for j in range(i + 1, len(tmp)):
            gap = min(gap, min(abs(tmp[j] - tmp[i]), 24 - tmp[j] + tmp[i]))
    ans = max(ans, gap)

print(ans)

Submission status: Accepted

Solution code:
I,a,i=input,24,int;n=i(I());d=[0]+sorted(list(map(i,I().split())))+[24]
for j in range(1,n+1,2):d[j]=24-d[j]
d.sort()
for j in range(n+1):a=min(a,abs(d[j+1]-d[j]))
print(a)

Submission status: Accepted

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
from fractions import Fraction
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
INF = float("inf")
MOD = 10**9+7

N = int(input())
A = list(map(int,input().split()))
d = defaultdict(int)

if 0 in A:
    print(0)
    exit()

for i in range(N):
    d[A[i]] += 1

T = [0]
W = []
for k in d.keys():
    if d[k] > 2:
        print(0)
        exit()
    if d[k] == 2:
        T.append(k)
        T.append(24-k)
    else:
        W.append(k)
#print(T,W)

ans = []

w = len(W)
K = 2 # 選択肢の数
for i in range(K**w):
    TF=[0]*w

    for j in range(w):
        TF[w-j-1] = i % K
        i //= K
    
    l = copy.deepcopy(T)
    for j in range(w):
        if TF[j] == 1:
            l.append(24-W[j])
        else:
            l.append(W[j])
            
    l.sort()
    l.append(24)
    #print(l)
    m = 24
    for j in range(1,len(l)):
        m = min(m,l[j] - l[j-1])
    ans.append(m)

print(max(ans))

Submission status: Accepted

Solution code:
n= int(input())
d= list(map(int,input().split()))
if n==1:print(d[0])
else:
    ddict={}
    for sd in d:ddict[sd]=ddict.get(sd,0)+1
    if 3<=max(ddict.values()):
        print(0);exit()
    elif 0 in ddict.keys():
        print(0);exit()
    elif 12 in ddict.keys() and ddict[12]==2:
        print(0);exit()
    else:
        fixtime=[0,24]
        ktime=[]
        for akey in ddict:
            if ddict[akey]==2:
                fixtime.append(akey)
                fixtime.append(24-akey)
            elif ddict[akey]==1:
                if akey==12:fixtime.append(12)
                else:ktime.append((akey,24-akey))
        gmin= min(d)
        skouho=sorted(fixtime)
        for i in range(len(skouho)-1):gmin=min(gmin,skouho[i+1]-skouho[i])
        if len(ktime)==0:print(gmin)
        else:
            longtime=0
            for i in range(2**len(ktime)):
                newtime=[]
                tempmin=24
                for j in range(len(ktime)):newtime.append(ktime[j][i>>j&1])
                temptime=sorted(fixtime+newtime)
                for k in range(len(temptime)-1):
                    tempmin=min(tempmin,temptime[k+1]-temptime[k])
                longtime=max(longtime,tempmin)
            print(longtime)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N = INT()
D = LIST()

time = [0]*13
time[0] = 1
for d in D:
	time[d] += 1

if 2 <= time[0] or 2 <= time[12]:
	print(0)
	exit()
elif any(3 <= x for x in time):
	print(0)
	exit()

time_ = [0]*24
time_koho = []
for i, cnt in enumerate(time[1:], 1):
	if cnt:
		if cnt == 2:
			time_[i] = 1
			time_[24-i] = 1
		else:
			time_koho.append(i)

ans = 0
for x in product([0, 1], repeat=len(time_koho)):
	time_tmp = time_.copy()
	for idx, y in enumerate(x):
		if y:
			time_tmp[24-time_koho[idx]] = 1
		else:
			time_tmp[time_koho[idx]] = 1

	time_diff = INF
	tmp = 0
	for j, c in enumerate(time_tmp[1:]+[1], 1):
		if c:
			time_diff = min(time_diff, j-tmp)
			tmp = j

	ans = max(ans, time_diff)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
d = list(map(int,input().split()))
if n >= 12:
    count = [0]*24
    count[0] += 2
    for i in d:
        count[i] += 1
        count[(24-i)%24] += 1
    if max(count) > 2:
        print(0)
    else:
        print(1)
    exit()
ans = 0
for i in range(1<<n):
    l = [0,24]
    for j in range(n):
        if i>>j & 1:
            l.append(d[j])
        else:
            l.append(24-d[j])
    l.sort()
    count = 24
    for j in range(len(l)-1):
        count = min(count,l[j+1]-l[j])
    ans = max(ans,count)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import Counter
N = int(input())
D = list(map(int, input().split()))
count_D = Counter(D)
if count_D.most_common()[0][1] >= 3:
    print(0)
    sys.exit()
ans = 0
for b in range(2**13):
    tmp = [0]
    for d in range(13):
        if count_D[d] == 2:
            tmp += [d, 24-d]
        elif count_D[d] == 1:
            if (b & 1):
                tmp += [d]
            else:
                tmp += [24 - d]
        b = b >> 1
    time_gap = 12
    for i in range(len(tmp)):
        for j in range(i+1, len(tmp)):
            time_gap = min(time_gap, min(abs(tmp[j]-tmp[i]), 24-tmp[j]+tmp[i]))
    ans = max(ans, time_gap)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
d = list(map(int, input().split()))
from itertools import product
if n>=13:
    from collections import Counter
    d.append(0)
    c = Counter(d)
    for i in range(13):
        c.setdefault(0)
    if c[0]<=1 and (c[12]<=1) and all([c[v]<=2 for v in range(1,12)]):
        ans = 1
    else:
        ans = 0
else:
    ans = 0
    for ind in product(*[range(2) for _ in range(n)]):
        vals = []
        for i in range(n):
            if ind[i]:
                vals.append(d[i])
            else:
                vals.append((24-d[i])%24)
        vals.append(0)
        res = 50
        for i in range(len(vals)):
            for j in range(i+1,len(vals)):
#                 print(i,j)
                v = abs(vals[i]-vals[j])
                res = min(res, min(v, 24-v))
        ans = max(ans, res)
print(ans)

Submission status: Accepted

Solution code:
def codefes17f_c():
    n = int(input())
    D = list(map(int, input().split()))
    D.sort()
    T = [0]
    for i, d in enumerate(D):
        if i%2: T.append(24-d)
        else: T.append(d)
    T.sort()
    ans = 12
    for i in range(n):
        ans = min(ans, T[i+1]-T[i])
    print(ans)

if __name__ == '__main__':
    codefes17f_c()

Submission status: Accepted

Solution code:
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy

def solve():
    n = getN()
    nums = getList()
    nums.sort()
    # if n == 1:
    #     print(0)
    #     return

    ji = [12]
    for i, num in enumerate(nums):
        if i % 2 == 0:
            ji.append(12-num)
        else:
            ji.append(12 + num)

    ans = INF
    ji.sort()
    for i, j in zip(ji, ji[1:]):
        ans = min(ans, j - i)

    ans = min(ans, (- ji[-1] + ji[0] + 24) % 24)
    # print(ji)
    print(ans)





def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
from copy import*
n=int(input())
d=[0]+list(map(int,input().split()))
c=dict(zip(list(range(13)),[0]*13))
for i in d:
  c[i]+=1
ans=0
for i in range(1,12):
  if c[i]==2:
    k=d.index(i)
    d[k]=24-d[k]
for i in range(1<<12):
  a=copy(d)
  cnt=24
  for j in range(1,12):
    if (i>>j)&1 and c[j]==1:
      k=d.index(j)
      a[k]=24-a[k]
  for j in range(n+1):
    for k in range(j+1,n+1):
      cnt=min(cnt,abs(a[j]-a[k]),24-abs(a[j]-a[k]))
  ans=max(cnt%24,ans)
print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil,pi,factorial
    from operator import itemgetter
    def I(): return int(input())
    def MI(): return map(int, input().split())
    def LI(): return list(map(int, input().split()))
    def LI2(): return [int(input()) for i in range(n)]
    def MXI(): return [[LI()]for i in range(n)]
    def SI(): return input().rstrip()
    def printns(x): print('\n'.join(x))
    def printni(x): print('\n'.join(list(map(str,x))))
    inf = 10**17
    mod = 10**9 + 7
#main code here!
    #全部異なるならbit全探索できそう
    #2つ以上同じものがあるとk以上同じものがある時　向きが逆だとして最小値候補に入れておく
    n=I()
    lis=LI()
    if 0 in lis:
        print(0)
        sys.exit()
    c=Counter(lis)
    ans=inf
    multi=[]
    for x in c.keys():
        #print(x)
        if c[x]>=3:
            print(0)
            sys.exit()
        elif c[x]>=2:
            ans=min(ans,x,24-2*x)
            multi.append(x)
    lis.append(0)
    lis=list(set(lis))
    u=len(lis)
    #print(lis)
    #ansは上限
    answers=[]
    #print(ans)
    for x in product([0,1],repeat=u):
        time=[]
        for i in range(u):
            if lis[i] in multi:
                time.append(lis[i])
                time.append(24-lis[i])
            elif x[i]==1:
                time.append(24-lis[i])
            else:
                time.append(lis[i])
        #print(time)
        z=ans
        for i in range(len(time)-1):
            for j in range(i+1,len(time)):
                z=min(z,24-abs(time[i]-time[j]),abs(time[i]-time[j]))   
        #print(z)
        answers.append(z)
        
    print(max(answers))
        
        
        
                
        
        
                
        
            
            
    
            
            
    


                
    
    
    
            
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from collections import Counter
from itertools import product

n = int(input())
d = Counter(list(map(int, input().split())) + [0])

ans, cnt = [], []
for num in d:
    if d[num] > (2 - (num in {0, 12})):
        print(0)
        exit()
    elif ((num in {0, 12}) and d[num] == 1) or d[num] == 2:
        ans += list(set([num, (24 - num) % 24]))
    elif d[num] == 1:
        cnt.append(num)

s = 0
if len(cnt) == 0:
    s = min(ans[i] - ans[i - 1] for i in range(1, len(ans)))
for bit in product([1, -1], repeat=len(cnt)):
    tmp = ans[:]
    tmp += [(ci - 12) * bi + 12 for bi, ci in zip(bit, cnt)]
    tmp = sorted(tmp + [i + 24 for i in tmp])
    stmp = min(tmp[i] - tmp[i - 1] for i in range(1, len(tmp)))
    s = max(s, stmp)
print(s)

Submission status: Accepted

Solution code:
from collections import Counter
from itertools import product

n = int(input())
d = Counter(list(map(int, input().split())) + [0])

ans, cnt = [], []
for num in d:
    if d[num] > (2 - (num in {0, 12})):
        print(0)
        exit()
    elif (num in {0, 12}) and d[num] == 1:
        ans.append(num)
    elif d[num] == 2:
        ans.append(num), ans.append(24 - num)
    elif d[num] == 1:
        cnt.append(num)

s = 0
if len(cnt) == 0:
    s = min(ans[i] - ans[i - 1] for i in range(1, len(ans)))
for bit in product([1, -1], repeat=len(cnt)):
    tmp = ans[:]
    tmp += [(ci - 12) * bi + 12 for bi, ci in zip(bit, cnt)]
    tmp = sorted(tmp + [i + 24 for i in tmp])
    stmp = min(tmp[i] - tmp[i - 1] for i in range(1, len(tmp)))
    s = max(s, stmp)
print(s)

Submission status: Accepted

Solution code:
n = int(input())
d = sorted(list(map(int, input().split())) + [0])

ans, cnt = [], 1
for num in d:
    ans.append(((num - 12) * cnt + 12) % 24)
    cnt *= -1

ans = sorted(ans + [i + 24 for i in ans])
s = min(ans[i] - ans[i - 1] for i in range(1, len(ans)))
print(s)

Submission status: Accepted

Solution code:
n = int(input())
d = sorted(list(map(int, input().split())) + [0])

bit, cnt = [0] * 24, 1
for num in d:
    bit[((num - 12) * cnt + 12) % 24] += 1
    cnt *= -1

if any(i > 1 for i in bit):
    print(0)
    exit()
ans = [i for i, li in enumerate(bit * 2) if li == 1]
s = min(ans[i] - ans[i - 1] for i in range(1, len(ans)))
print(s)

Submission status: Accepted

Solution code:
from collections import Counter
from itertools import product


def solve(LIST):
    stmp = [i for i, li in enumerate(LIST * 2) if li == 1]
    S = min(stmp[i] - stmp[i - 1] for i in range(1, len(stmp)))
    return S


n = int(input())
d = Counter(list(map(int, input().split())) + [0])

if any(d[num] > (2 - (num in {0, 12})) for num in d):
    print(0)
    exit()

ans, cnt = [0] * 24, []
for num in d:
    if (num in {0, 12}) and d[num] == 1:
        ans[num] = 1 
    elif d[num] == 2:
        ans[num], ans[24 - num] = 1, 1
    elif d[num] == 1:
        cnt.append(num)

s = 0
if len(cnt) == 0:
    s = max(s, solve(ans))
for bit in product([1, -1], repeat=len(cnt)):
    tmp = ans[:]
    for bi, ci in zip(bit, cnt):
        tmp[(ci - 12) * bi + 12] = 1
    s = max(s, solve(tmp))
print(s)

Submission status: Accepted

Solution code:
from collections import Counter
from itertools import product


def solve(LIST):
    S = 24
    slvtmp = [i for i, li in enumerate(LIST * 2) if li == 1]
    for i in range(1, len(slvtmp)):
        S = min(S, slvtmp[i] - slvtmp[i - 1])
    return S


n = int(input())
d = Counter(list(map(int, input().split())) + [0])

if any(d[num] > (2 - (num in {0, 12})) for num in d):
    print(0)
    exit()

ans, cnt = [0] * 24, []
for num in d:
    if (num in {0, 12}) and d[num] == 1:
        ans[num] = 1 
    elif d[num] == 2:
        ans[num], ans[24 - num] = 1, 1
    elif d[num] == 1:
        cnt.append(num)

s = 0
if len(cnt) == 0:
    s = max(s, solve(ans))
for bit in product([1, -1], repeat=len(cnt)):
    tmp = ans[:]
    for bi, ci in zip(bit, cnt):
        tmp[(ci - 12) * bi + 12] = 1
    s = max(s, solve(tmp))
print(s)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n = int(readline())
    d = list(map(int, readline().split()))
    d.sort()
    t = [d[0]]
    s = min(24 - d[0], d[0])

    for i in range(1, n):
        cur = d[i]
        am = cur
        pm = 24 - cur
        s_am = s
        s_pm = s
        for j in range(i):
            prev = t[j]
            s_am = min(s_am, min(24 - abs(am - prev), abs(am - prev)))
            s_pm = min(s_pm, min(24 - abs(pm - prev), abs(pm - prev)))

        if s_am > s_pm:
            t.append(am)
            s = s_am
        else:
            t.append(pm)
            s = s_pm

    print(s)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

def main():
	n=II()
	D=LI()+[0]

	D.sort()
	#print(D)

	DD=[]

	for i,v in enumerate(D):
		if i%2==0:
			DD.append(v)
		else:
			DD.append(24-v)
	DD.sort()
	DD.append(24)

	#print(DD)

	ans=25

	for i,j in zip(DD[:-1],DD[1:]):
		ans=min(ans,j-i)
	print(ans)











if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
n = int(input())
dl = list(map(int, input().split()))

if 0 in dl:
    print(0)
    exit()

dl.sort()
dl1 = [0,24]
dl2 = [0,24]
for i, d in enumerate(dl):
    if i%2 == 0:
        dl1.append(d)
        dl2.append(24-d)
    else:
        dl1.append(24-d)
        dl2.append(d)

dl1.sort()
dl2.sort()

min_1 = 24
for a,b in zip(dl1[1:],dl1[:-1]):
    diff = a-b
    min_1 = min(min_1,diff)

min_2 = 24
for a,b in zip(dl2[1:],dl2[:-1]):
    diff = a-b
    min_2 = min(min_2,diff)

ans = max(min_1,min_2)
print(ans)

Submission status: Accepted

Solution code:
from itertools import product
import random

def solve(n,dl):
    # n = int(input())
    # dl = list(map(int, input().split()))

    if 0 in dl:
        return 0

    doubles = []
    dl1 = []
    dl2 = []
    for i in range(1,13):
        i_cnt = dl.count(i)
        if i_cnt > 2:
            return 0
        elif i_cnt == 2:
            dl2.append(24-i)
            dl2.append(i)
        elif i_cnt == 1:
            dl1.append(i)        

    ans = 0
    ite = list(product(range(2),repeat=len(dl1)))
    for pattern in ite:
        dl24 = [0,24]
        for i, v in enumerate(pattern):
            if v == 1:
                dl24.append(24-dl1[i])
            else:
                dl24.append(dl1[i])
        dl24 = dl24 + dl2
        dl24.sort()
        diff_min = 24
        # print(dl24)
        if len(dl24) == 1:
            ans = max(ans, min(dl24[0], 24-dl24[0]))
        else:
            for a,b in zip(dl24[:-1],dl24[1:]):
                diff = b-a
                if diff != 24:
                    diff_min = min(diff_min,diff)
            ans = max(diff_min,ans)
    return ans


def solve2(n,dl):
    ite = list(product(range(2),repeat=len(dl)))
    ans = 0
    for pattern in ite:
        dl_new = [0]
        for i, v in enumerate(pattern):
            if v == 1:
                dl_new.append(24-dl[i])
            else:
                dl_new.append(dl[i])
        dl_new.sort()
        diff_min = 24
        for a,b in zip(dl_new[:-1], dl_new[1:]):
            diff = b-a
            diff_min = min(diff_min, diff)
        ans = max(ans,diff_min)
    return ans


if __name__ == "__main__":
    n = int(input())
    dl = list(map(int, input().split()))
    ans = solve(n,dl)
    print(ans)
    # for _ in range(10):
    #     n = random.randint(1,10)
    #     dl = [random.randint(1,12) for _ in range(n)]
    #     ans1 = solve(n, dl[:])
        # ans2 = solve2(n,dl[:])
        # if ans1 != ans2:
        #     print(n)
        #     print(dl)
        #     print(ans1)
        #     print(ans2)
        #     print('----')

Submission status: Accepted

Solution code:
from collections import Counter
from itertools import product


N = int(input())
D = list(map(int, input().split()))
D_cnt = Counter(D)
if N >= 24 or D_cnt[0] > 0 or D_cnt[12] > 1 or any(D_cnt[i] > 2 for i in range(1, 12)):
    print(0)
    exit()
clock = [0, 24]
undet = []
if 12 in D_cnt:
    clock.append(12)
for i in range(1, 12):
    if D_cnt[i] == 2:
        clock.append(i)
        clock.append(24 - i)
    elif D_cnt[i] == 1:
        undet.append(i)

ans = 0
for rp in product([0, 1], repeat=len(undet)):
    candidate = clock[:]
    for j, is_flipped in enumerate(rp):
        candidate.append(undet[j]) if is_flipped else candidate.append(24 - undet[j])
    candidate.sort()
    ans = max(ans, min(ca - cb for cb, ca in zip(candidate, candidate[1:])))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
D = list(map(int,input().split()))
s = min(D)
if 12 in D:
    for i in range(N):
        if D[i]!=12:
            s = min(s,12-D[i])
    D.remove(12)
D = sorted(D)
E = []
for i in range(len(D)):
    if i%2==0:
        E.append(D[i])
    else:
        E.append(24-D[i])
for i in range(len(E)-1):
    for j in range(i+1,len(E)):
        a = E[i]
        b = E[j]
        d = abs(a-b)
        if d>12:
            d = 24-d
        s = min(s,d)
print(s)