최대 1 분 소요

part41. [PCCP 기출문제] 1번 / 붕대 감기

js ver 1.0

function solution(bandage, health, attacks) {
    const [duration, heal, plus] = bandage;
    let prv, remain, result = health;
    
    for(const [second, damage] of attacks){
        if(result <= 0) {
            return -1;
        }
        
        if (prv) {
            remain = second - prv - 1;

            if (remain) {
                result += remain * heal + Math.floor(remain / duration) * plus;
    
                if (result > health) {
                    result = health;
                }
            }
        }

        prv = second;
        result -= damage;
    }
    
    return result <= 0 ? -1 : result;
}

실행결과_js ver 1.0


문제의 오류

function solution(bandage, health, attacks) {
    return attacks.reduce((result, [sec, attack], idx) => {
        if (result > 0) {
            if (idx) {
                const remain = sec - attacks[idx - 1][0] - 1;

                if (remain) {
                    result += remain * bandage[1] + Math.floor(remain / bandage[0]) * bandage[2];

                    if (result > health) {
                        result = health;
                    }
                }
            }

            return result - attack || -1;
        } else {
            return -1;
        }
    }, health);
}

업데이트: