본문 바로가기

백준 1487 - 물건팔기 (reduce) JS 본문

개발/algorithm

백준 1487 - 물건팔기 (reduce) JS

자전하는명왕성 2023. 9. 12. 09:31

https://www.acmicpc.net/problem/1487 

해당 문제는 판매자가 최대 이윤을 남길 수 있는 판매가격을 구하는 문제이다.

소비자의 희망 구매 가격과 배송비를 고려하여 문제를 풀어야 한다.

 

아래는 반복문 고차함수(forEach), 와 누산 고차함수(reduce)를 이용한 풀이를 소개한다.

const fs = require('fs')
const input = fs.readFileSync(process.platform === "linux" ? "/dev/stdin":"입력.txt")
  .toString().trim().split('\n')

function solution(data) {
  let [_, ...arr] = data.map(el=> el.split(' ').map(Number))
  arr = arr.sort((a,b)=> a[0] - b[0])
  const prices = arr.map(el => el[0])
  
  // forEach 활용 시
  const profits = prices.map((price)=> {
  // forEach 의 경우에는 누산 결과를 temp 변수에 담는다
    let temp = 0
    arr.forEach((el)=> {
      const [hope, delivery] = el
      temp += price > hope ? 0
      : price - delivery < 0 ? 0
      : price - delivery
    })
    return temp
  })
  
  // reduce 활용 시
  const profits = prices.map((price)=> {
    return arr.reduce((acc,cur)=> {
      const [hope, delivery] = cur
      return acc + 
        ( price > hope ? 0 
        : price - delivery < 0 ? 0 
        : price - delivery)
    }, 0)
  })
  
  const max = Math.max(...profits)
  console.log(max !== 0 ? arr[profits.indexOf(max)][0] : 0)
}

solution(input)

 

그리고 두 코드를 비교해보았는데 메모리는 무의미한 차이, 소모 시간상으로는 reduce를 사용한 코드가 약간 더 짧았다.

처음 해보는 실험이라 유의미하다고는 볼 수 없지만, 비슷한 경우가 생기거든 또 실험해봐야겠다.

 

Comments