1+ import java .util .*;
2+
3+ class Food implements Comparable <Food > {
4+
5+ private int time ;
6+ private int index ;
7+
8+ public Food (int time , int index ) {
9+ this .time = time ;
10+ this .index = index ;
11+ }
12+
13+ public int getTime () {
14+ return this .time ;
15+ }
16+
17+ public int getIndex () {
18+ return this .index ;
19+ }
20+
21+ // 시간이 짧은 것이 높은 우선순위를 가지도록 설정
22+ @ Override
23+ public int compareTo (Food other ) {
24+ return Integer .compare (this .time , other .time );
25+ }
26+ }
27+
28+ class Solution {
29+ public int solution (int [] food_times , long k ) {
30+ // 전체 음식을 먹는 시간보다 k가 크거나 같다면 -1
31+ long summary = 0 ;
32+ for (int i = 0 ; i < food_times .length ; i ++) {
33+ summary += food_times [i ];
34+ }
35+ if (summary <= k ) return -1 ;
36+
37+ // 시간이 작은 음식부터 빼야 하므로 우선순위 큐를 이용
38+ PriorityQueue <Food > pq = new PriorityQueue <>();
39+ for (int i = 0 ; i < food_times .length ; i ++) {
40+ // (음식 시간, 음식 번호) 형태로 우선순위 큐에 삽입
41+ pq .offer (new Food (food_times [i ], i + 1 ));
42+ }
43+
44+ summary = 0 ; // 먹기 위해 사용한 시간
45+ long previous = 0 ; // 직전에 다 먹은 음식 시간
46+ long length = food_times .length ; // 남은 음식의 개수
47+
48+ // summary + (현재의 음식 시간 - 이전 음식 시간) * 현재 음식 개수와 k 비교
49+ while (summary + ((pq .peek ().getTime () - previous ) * length ) <= k ) {
50+ int now = pq .poll ().getTime ();
51+ summary += (now - previous ) * length ;
52+ length -= 1 ; // 다 먹은 음식 제외
53+ previous = now ; // 이전 음식 시간 재설정
54+ }
55+
56+ // 남은 음식 중에서 몇 번째 음식인지 확인하여 출력
57+ ArrayList <Food > result = new ArrayList <>();
58+ while (!pq .isEmpty ()) {
59+ result .add (pq .poll ());
60+ }
61+ // 음식의 번호 기준으로 정렬
62+ Collections .sort (result , new Comparator <Food >() {
63+ @ Override
64+ public int compare (Food a , Food b ) {
65+ return Integer .compare (a .getIndex (), b .getIndex ());
66+ }
67+ });
68+ return result .get ((int ) ((k - summary ) % length )).getIndex ();
69+ }
70+ }
0 commit comments