❓❓❓ 마구간 정하기 : Binary Search

frenchkebab·2021년 8월 30일
0
post-thumbnail

Solution 풀이

function count(stable, mid) {
  let ep = stable[0];
  let cnt = 1;
  for (let x of stable) {
    if (x - ep >= mid) {
      ep = x;
      cnt++;
    }
  }
  return cnt;
}

function solution(c, stable) {
  let answer;
  stable.sort((a, b) => a - b);
  let l = 1;
  let r = stable[stable.length - 1];
  while (l <= r) {
    let mid = parseInt((l + r) / 2);
    if (count(stable, mid) >= c) {
      answer = mid;
      l = mid + 1;
    } else r = mid - 1;
  }
  return answer;
  console.log(answer);
}

let arr = [1, 2, 8, 4, 9];
console.log(solution(3, arr));
  • 뮤직 비디오 문제와 더불어 여러 번 풀면서 내 것으로 만들어야겠다.
  • 아직도 이런 문제 만나면 머리가 굳고 발상이 잘 떠오르지 않는 것 같다 ㅠㅠㅠㅠ
profile
Blockchain Dev Journey

0개의 댓글