Bleeding edge

[LeetCode] 1578. Minimum Time to Make Rope Colorful - 자바스크립트 0624 본문

코딩테스트 공부

[LeetCode] 1578. Minimum Time to Make Rope Colorful - 자바스크립트 0624

codevil 2022. 6. 24. 13:30

https://leetcode.com/problems/minimum-time-to-make-rope-colorful/

 

Minimum Time to Make Rope Colorful - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

요즘 map, reduce, filter를 자주쓰다보니 block scope에 대한 공부가 잘되는 것 같다.

1. 이 문제는 글자에서 다음글자가 같은지 다른지를 체크해야하고, 겹치는 글자가 2개이상인지 확인해야한다 따라서, 글자가 들어갈 last, 겹치는 글자를 체크하는 list, 그리고 종합을 해줄 result를 선언한다.

    const result = []
    let last
    let list = []

 

2-1. 주어진 colors에서, colors[i]와 last가 같으면, list에 neededTime[i]를 push한다.

2-2 만일, colors[i] last가 다르다면

2-2-1 만일 list에 들어있는 숫자가 1보다 크다면, result에 list를 push한다

2-2-2 2-2의 모든 경우에 last = colors[i], list = [neededTime[i]]를 해준다.

    for (let i = 0; i < colors.length; i++) {
        if (colors[i] === last) {
            list.push(neededTime[i])
        } else {
            if (list.length > 1) {
                result.push(list)
            }
            last = colors[i]
            list = [neededTime[i]]
        }}

위의 조건문을 만들면, 2개가 연속한 경우에는, result에 [[1,2], [1,1]] 와 같이 array in array 모양이 된다. 문제는 마지막에 연속한 문자가 들어온 경우가 있다고하면 result에 숫자가 들어가지 않기 때문에 3번을 실행한다

3. 2번에 있었던 1보다 크면 result에 list push를 한다.

    if (list.length > 1) {
        result.push(list)
    }

4. result에 각성분을 다루기 위하여 map을 사용한다. map에서 받는 변수는 item이라고 한다면, item의 최고 값을 max라고하고, 이 item들의 합을 sum이라고 한다. map에 블록 스코프 값을 sum - max로 return 시킨다. 이러면, result에는 연속한 풍선중 작은 것들만 없앤것과 같아진다. 하지만 지금 값은 이 result에 있는 component들의 값이다.

5. 마무리를 위하여 reduce로 값을 더한다

    return result.map((item) => {
        const max = Math.max(...item)
        const sum = [...item].reduce((a, b) => a + b, 0)
        return sum - max
    }).reduce((a, b) => a + b, 0)

 

최종 풀이

var minCost = function (colors, neededTime) {
    const result = []
    let last
    let list = []
    for (let i = 0; i < colors.length; i++) {
        if (colors[i] === last) {
            list.push(neededTime[i])
        } else {
            if (list.length > 1) {
                result.push(list)
            }
            last = colors[i]
            list = [neededTime[i]]
        }}
    if (list.length > 1) {
        result.push(list)
    }
    return result.map((item) => {
        const max = Math.max(...item)
        const sum = [...item].reduce((a, b) => a + b, 0)
        return sum - max
    }).reduce((a, b) => a + b, 0)
};