티스토리 뷰

반응형

■ 문제

원본 사이트: https://www.hackerrank.com/challenges/mark-and-toys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting 

 

Mark and Toys | HackerRank

You are Mark's best friend and have to help him buy as many toys as possible.

www.hackerrank.com

 

난이도: Easy

최대 스코어: 35

 

● 문제 요약

  • Mark는 아들을 위한 장난감을 사고 싶어함
  • Mark가 지출할 수 있는 금액은 정해져있음
  • 최대한 많은 수의 장난감을 사려고 함
  • 장난감 가격 목록(prices)과 지출 가능 금액(k)이 주어질 때, Mark가 살 수 있는 최대 선물 수를 return

 

예시:

prices = [1, 2, 3, 4]
k = 7
  • [1, 2, 3] --> 금액: 6, 개수: 3개
  • [3, 4] --> 금액: 7, 개수: 2개

==> 최대 선물 수는 3개

 

 

■ 문제 풀이

장난감 가격 목록인 prices를 오름차순으로 정렬한 뒤, 장난감 가격의 합계가 지출 가능 금액 k를 초과하지 않는 범위까지 count해서 return한다.

 

● 완성 코드 - 35 Points (Max)

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the maximumToys function below.
function maximumToys(prices, k) {
    let sum = 0;
    let count = 0;
    prices.sort((a, b) => { return a - b; });
    for(let i=0; i<prices.length; i++){
        sum += prices[i];
        if(sum > k){
            return count;
        }else{
            count++;
        }
    }
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const nk = readLine().split(' ');

    const n = parseInt(nk[0], 10);

    const k = parseInt(nk[1], 10);

    const prices = readLine().split(' ').map(pricesTemp => parseInt(pricesTemp, 10));

    let result = maximumToys(prices, k);

    ws.write(result + "\n");

    ws.end();
}
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함