알고리즘(Algorithm)

프로그래머스 - 체육복(Greedy) [JS]

Hun-bot 2023. 1. 13. 10:57
728x90
반응형

풀이

function solution(n, lost, reserve) {
  let checkLost=lost.filter(i=>!reserve.includes(i)).sort()
  let checkReserve=reserve.filter(i=>!lost.includes(i)).sort()
  checkLost=checkLost.filter(i=>{
    let temp=checkReserve.find(j=>Math.abs(i-j)<=1)
    if(!temp) return true
    checkReserve=checkReserve.filter(k=>k!==temp)
  })
  return n-checkLost.length
}

lost와 reserve에 둘 다 있는 숫자를 먼저 제거후 정렬-> 체육복을 잃어버렸지만 여분을 가진 친구들

ex) solution(3, [1], [1])

 

체육복을 잃어버린 학생들의 배열 ( checkLost )의 값이 체육복 여분이 있는 학생들 ( checkReserve )의 값과 1차이가 난다면 체육복을 빌려줄수 있다. ( Math.abs -> 절댓값 )

 

filter 메서드 사용이유 -> 잃어버린 학생들이 체육복을 받으면 체육 수업을 들을  수 있으므로 checkLost 배열에서 제거

 

find 메서드를 통해 찾은 값이 없다면 filter 메서드 종료

체육복 여분을 빌려줬으므로 여분을 빌려준 학생은 배열에서 제거

    if(!temp) return true
    
    checkReserve=checkReserve.filter(k=>k!==temp)

 

728x90
반응형