본문 바로가기
👩‍💻 Programming/Coding Test 문제 풀이

[이코테] 그리디_큰 수의 법칙

by codingBear 2022. 9. 15.
728x90
반응형

 이번 글은 '이것이 취업을 위한 코딩 테스트다 with 파이썬' 내 문제를 풀고, 정답 코드를 정리한 것입니다.


문제


풀이 과정

 이번 문제 풀이의 핵심은 바로 배열을 정렬하여 최댓값을 찾아내는 것이다. 문제를 풀 때는 최댓값과 그 다음으로 큰 값만이 필요하다. 내 풀이의 경우 입력을 받은 배열을 내림차순으로 정렬하여 max와 next 변수에 각각 최댓값과 두 번째로 큰 값을 할당한다. 그 다음 if문을 통해 max가 next보다 클 경우 정답에 할당된 빈 배열의 길이가 M이 될 때까지 while문을 돌린다. 이때 while문 내에서 K만큼 for문을 돌며 가장 큰 값을 정답 배열에 push한 다음 두 번째로 큰 값을 정답 배열에 한 번 push한다. 만일 max와 next가 같을 경우 굳이 번갈아가며 더하기를 할 필요가 없으므로 max값만 정답 배열에 push해준다. 이렇게 정답 배열에 할당된 숫자들을 reduce() 메서드를 활용해 반환하면 정답이 나온다.


정답 코드

My Solution
function mySolution(_n, _m, _k, _arr) {
  let ans = [];
  _arr = _arr.sort((a, b) => b - a);
  const max = _arr[0];
  const next = _arr[1];

  if (max > next) {
    while (ans.length < _m) {
      for (let i = 0; i < _k; i++) {
        ans.push(max);
      }
      ans.push(next);
    }
  } else if (max === next) {
    while (ans.length < _m) {
      ans.push(max);
    }
  }

  return ans.reduce((prev, curr) => prev + curr, 0);
}
Answer
function answer(_n, _m, _k, _arr) {
  _arr.sort((a, b) => a - b);
  const first = _arr[_n - 1];
  const second = _arr[_n - 2];

  ret = 0;

  while (true) {
    for (let i = 0; i < _k; i++) {
      if (_m === 0) break;
      ret += first;
      _m -= 1;
    }
    if (_m === 0) break;
    ret += second;
    _m -= 1;
  }

  return ret;
}

함께 보기

sort()

 

Array.prototype.sort() - JavaScript | MDN

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units val

developer.mozilla.org

reduce()

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the a

developer.mozilla.org

 

728x90
반응형

댓글