Hyunebee

회의를 몇번 들어갈수있나? 본문

Java/코테

회의를 몇번 들어갈수있나?

Hyunebee 2022. 5. 19. 12:19

그리디

 

여기서 생각을 해야할 것은 종료와 동시에 시작할 수 있다는것

종료시간을 기준으로 정렬하지만 종료시간이 모두 같을 경우는 시작 시간 기준으로 정렬해 계산

lamda 식으로 처음에 했지만 종료시간이 같을 경우를 포함할 수 없어 Compareble<T>로 구현

import java.util.*;

class Time implements Comparable<Time>{
    int start;
    int end;

    public Time(int start, int end) {
        this.start = start;
        this.end = end;
    }

    //중요
    //종료시간 <= 시작시간이라면 시작가능
    //종료 시간이 모두 같을 경우는 시작시간 순으로 정렬해 처리해줘야함
    @Override
    public int compareTo(Time o) {
        if(this.end == o.end){
            return this.start - o.start;
        }
        return this.end - o.end;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(); // 배열의 크기
        ArrayList<Time> arrayList = new ArrayList<>();


        for(int i = 0; i < N; i++){
            int height = sc.nextInt();
            int weight = sc.nextInt();
            arrayList.add(new Time(height, weight));
        }



        Main T = new Main();
        System.out.println(T.solution(N,arrayList));
    }

    public int solution(int k, ArrayList<Time> arr){
        int cnt = 0;
        int currentTime = 0;
        Collections.sort(arr);
        for(int i = 0 ; i < k; i++){
            if(arr.get(i).start >= currentTime){
                currentTime = arr.get(i).end;
                cnt++;
            }
        }


      return cnt;
    }
}
import java.util.*;

class Time implements Comparable<Time>{
    int start;
    int end;

    public Time(int start, int end) {
        this.start = start;
        this.end = end;
    }

    //중요
    //종료시간 <= 시작시간이라면 시작가능
    //종료 시간이 모두 같을 경우는 시작시간 순으로 정렬해 처리해줘야함
    @Override
    public int compareTo(Time o) {
        if(this.end == o.end){
            return this.start - o.start;
        }
        return this.end - o.end;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(); // 배열의 크기
        ArrayList<Time> arrayList = new ArrayList<>();


        for(int i = 0; i < N; i++){
            int height = sc.nextInt();
            int weight = sc.nextInt();
            arrayList.add(new Time(height, weight));
        }



        Main T = new Main();
        System.out.println(T.solution(N,arrayList));
    }

    public int solution(int k, ArrayList<Time> arr){
        int cnt = 0;
        int currentTime = 0;
        Collections.sort(arr);
        for(int i = 0 ; i < k; i++){
            if(arr.get(i).start >= currentTime){
                currentTime = arr.get(i).end;
                cnt++;
            }
        }


      return cnt;
    }
}

'Java > 코테' 카테고리의 다른 글

최대 강연료는 얼마?  (0) 2022.05.19
동시에 몇명까지 가능할까?  (0) 2022.05.19
씨름선수선발하기  (0) 2022.05.19
연속해서 가장 긴 수  (0) 2022.05.19
K가 되는 수  (0) 2022.05.18