2021 KAKAO BLIND RECRUITMENT - 광고 삽입 (Level 3)

 

https://programmers.co.kr/learn/courses/30/lessons/72414


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def solution(_play_time, _adv_time, _logs):
    def str2int(s):
        h, m, s = s.split(':')
        return 3600*int(h) + 60*int(m) + int(s)
    def int2str(secs):
        h = secs // 3600
        m = (secs % 3600)//60
        s = secs % 60
        return f"{h:02}:{m:02}:{s:02}"

    play_time = str2int(_play_time)
    adv_time  = str2int(_adv_time)

    logs = [(str2int(log.split('-')[0]), str2int(log.split('-')[1])) for log in _logs]
    logs = sorted([(log[0], 0) for log in logs]+[(log[1], 1) for log in logs])

    val = 0
    n_dups = [val]*play_time
    prev_time = 0
    for time, type in logs:
        n_dups[prev_time:time] = [val]*(time-prev_time)
        if type == 0:  # start
            val += 1
        else:
            val -= 1
        prev_time = time

    max_val = 0
    max_s   = 0
    vals    = []

    '''
    play_time = 10
    adv_time  = 3

    s = 0 1 ~ 7   = range(play_time-adv_time+1) = range(8)
    e = 3 4 ~ 10

    '''

    for s in range(play_time-adv_time+1):
        e = s + adv_time
        if s == 0:
            max_val = val = sum(n_dups[s:e])
            max_s   = s
        else:
            val = val - n_dups[s-1] + n_dups[e-1]
            if val > max_val:
                max_val = val
                max_s   = s

    return int2str(max_s)

Complexity

$O(nlogn+m)$

  • $n$: |logs|
  • $m$: |play_time|