Computer Science/알고리즘

백준 Java | BOJ 2805 나무 자르기

토마토. 2023. 1. 31. 15:14

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static int N;
    public static int M;
    public static int[] height;

    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream("src/DAY02/P2805/input.txt"));
        Scanner scanner = new Scanner(System.in);
        N = scanner.nextInt();
        M = scanner.nextInt();
        height = new int[N];
        int max = 0;
        for (int i=0;i<N;i++){
            height[i] = scanner.nextInt();
            if (height[i] > max){
                max = height[i];
            }
        }

        int answer = 0;
        int left = 0;
        int right = max;
        int mid = 0;

        while (left <= right){
            mid = (left + right) / 2;
            // print(left, right, mid);
            double value = roi(mid);
            // System.out.println(value);
            if (value > M){
                if (answer < mid){
                    answer = mid;
                }
                left = mid+1;
            } else if (value==M) {
                answer = mid;
                break;
            } else {
                right = mid-1;
            }
        }
        System.out.println(answer);
    }
    public static void print(int left, int right, int mid){
        System.out.println("l : " + left + ", m: " + mid + ", r : " + right);
        for (int i=0;i<N;i++){
            System.out.print(height[i]);
        }
        System.out.println();
    }
    public static double roi(int mid){
        double value = 0;
        for (int i=0;i<N;i++){
            if (height[i] > mid){
                value += (double)(height[i] - mid);
            }
        }
        return value;
    }
}