seungriyou / algorithm-study

알고리즘 & SQL 문제 풀이 기록
0 stars 0 forks source link

[LC] 621. Task Scheduler #70

Open seungriyou opened 3 months ago

seungriyou commented 3 months ago

https://leetcode.com/problems/task-scheduler/

Approach

most frequent element를 이용하는 greedy 문제이다.

image


Idea 1: w/o Heap (1-Pass)

ref: sol1, sol2

[!tip] most frequent task부터 순서대로 최소 간격(n)을 사이에 두고 배치해나가는 것이 포인트!



Idea 2: w/ Max Heap

ref: sol

max heap q를 통해 most frequent 한 순서대로 각 task의 등장 횟수값을 pop한다.

이때의 포인트는, n + 1 만큼의 interval을 cycle로 잡아

  1. cycle 내 interval 수만큼 most frequent 한 순서대로 pop 하면서 tmp(등장 횟수 업데이트용) 및 tmp_time에 기록하고

    이렇게 하면 한 cycle 내에서는 같은 task를 두 번 이상 pop 할 수 X

  2. q에 원소가 남아있다면 이번 cycle을 꽉 채웠으며 다음 cycle에서 pop 할 task가 남아있다는 뜻이므로 cycle을 더해주고, 아니라면 이번 cycle을 꽉 채우지 못했을 수도 있으므로 이번 turn에서 기록한 tmp_time을 더해준다

    res += cycle if q else tmp_time

는 것이다.


Complexity

seungriyou commented 3 months ago

https://leetcode.com/problems/task-scheduler/editorial/

editorial 댓글에 있는 유사 문제도 풀어보기! (greedy + heap)