본문 바로가기

코딩테스트

[프로그래머스] [python / Java] 1단계 : 덧칠하기

정답 코드 (python)

def solution(n, m, section):
    answer = 1
    paint = section[0] # 덧칠 시작점
    for i in range(1,len(section)):
        k = section[i] - paint
        if k >= m:
            answer += 1
            paint = section[i]
    return answer

덧칠 시작점을 잡는 부분에서 헤맸다. 

첫번째 페인트칠을 시작하는걸로 answer = 1로 선언해두고 section의 원소를 차례로 돌아가며 덧칠 시작점부터

각 원소까지의 거리를 계산하며 페인트칠을 다시 할것인지 결정한다.

정답 코드 (Java)

class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 1;
        int paint = section[0];
        int l = section.length;
        for (int i=1; i<l; i++) {
            if ((section[i] - paint) >= m) {
                answer += 1;
                paint = section[i];
            }
        }
        return answer;
    }
}