흙금이네 블로그

[BOJ] 15565 - 귀여운 라이언 (Python, JavaScript) 본문

알고리즘

[BOJ] 15565 - 귀여운 라이언 (Python, JavaScript)

흙금 2023. 5. 31. 13:07

 

 

아이디어

 

투포인터로 라이언 인형을 K개 포함하는 연속된 집합 크기의 최솟값을 구한다.

 

 

풀이 #1 (Python)

 

def solution():
    N, K = map(int, input().split())
    toys = tuple(map(lambda x: x == '1', input().split()))
    ryans = []
    for i in range(N):
        if toys[i]:
            ryans.append(i)
    M = len(ryans)
    res = -1
    for e in range(K-1, M):
        s = e-K+1
        d = ryans[e]-ryans[s]+1
        if d < res or res < 0:
            res = d
    print(res)

solution()

 

 

 

풀이 #2 (JavaScript)

 

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');

function solution() {
    const [N, K] = input[0].split(' ').map(Number);
    let ryans = [];
    input[1].split(' ').forEach((x, i) => {
        if (x === '1') ryans.push(i);
    });
    let res = -1;
    for (let e=K-1; e<ryans.length; e++) {
        const s = e-K+1;
        const d = ryans[e]-ryans[s]+1;
        if (d < res || res < 0) res = d;
    }
    console.log(res);
}

solution();

 

Comments