본문 바로가기

IT/Python

[codility] Greedy TieRopes

https://app.codility.com/programmers/lessons/16-greedy_algorithms/tie_ropes/

 

TieRopes coding task - Learn to Code - Codility

Tie adjacent ropes to achieve the maximum number of ropes of length >= K.

app.codility.com

 

문제: 배열 A에 줄 길이가 담겨져 있다. 인접한 (ex. A[0], A[1]) 줄은 묶을 수 있고 묶은 줄은 또 묶을 수 있다. 

A 에서 K 이상의 줄은 몇 개 만들 수 있는 지 반환

 

 

1
2
3
4
5
6
7
8
9
10
11
12
def solution(K, A):
    cnt = 0 
    rope_len = 0
 
    for l in A:
        rope_len += l
 
        if rope_len >= K :
            cnt += 1 
            rope_len = 0
 
    return cnt
cs

 

배열 순서대로 더해서 K 이상이 되면 0 으로 초기화 하고 갯수 증가하는 식으로 간단하게 풀었다.