알고리즘/이분탐색

[백준] 2805번 나무 자르기 #Java

VIPeveloper 2022. 5. 9. 23:13
728x90
반응형
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int [] arr = new int [N];

        st = new StringTokenizer(br.readLine());
        int lo=0,hi=Integer.MIN_VALUE;
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
            if(arr[i] > hi){
                hi = arr[i];
            }
        }

        while (lo < hi){
            int mid = (lo + hi) / 2;
            int sum = 0;
            
            for (int i = 0; i < N; i++) {
                int tmp = (arr[i]-mid);
                if(arr[i] - mid >0){
                    sum+=tmp;
                }
            }
            if(sum < M){
                hi = mid;
            }else{
                lo = mid+1;
            }
        }
        System.out.println(lo-1);
    }
}
728x90
반응형

'알고리즘 > 이분탐색' 카테고리의 다른 글

[백준] 1654번 : 랜선 자르기 #Java  (0) 2022.05.08
[백준] 10816 숫자카드 2 #Java  (0) 2022.05.07