728x90

https://school.programmers.co.kr/learn/courses/30/lessons/148653#qna

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

탐욕Greedy 알고리즘을 사용해 풀어보자 

 

자신의 자리가 5 이상이라면 올림으로 처리하는것이 더 낫다 

e.g) 95인 경우에는 10*9 + 1*5 총 14회 보다 , 100*1 - 1*5 해서 총 6회로 나오는것이 더 적게 든다 

 

function solution(storey) {
    let ary = String(storey).split("").map(Number); 
    let carry = 0; //올림수
    let total = 0; 

    for (let i = ary.length - 1; i >= 0; i--) { 
        let current = ary[i] + carry;

        if (current > 5) {
            carry = 1;
            total += 10 - current;
        } else if (current === 5 && i > 0 && ary[i - 1] >= 5) {
            carry = 1;
            total += 5;
        } else {
           
            carry = 0;
            total += current;
        }
    }

  
    if (carry > 0) {
        total += carry;
    }

    return total;
}

 

555의 경우에는 올림을 해서 계산을 할 때와 올림을 적용하지 않았을때 둘 다 15회로 값이 동일하다 

728x90

+ Recent posts