import java.util.*;
class Main {
public int count(int m, int[] arr) {
int cnt = 1;
int sum = 0;
int tmp = 0;
for (int i = 0; i < arr.length; i++) {
tmp = sum + arr[i];
if (tmp <= m) {
sum = tmp;
} else {
sum = arr[i];
cnt++;
}
}
return cnt;
}
public int solution(int N, int M, int[] arr) {
int answer = Integer.MAX_VALUE;
int lt = 1, rt = 0, mid = 0;
for (int x : arr)
rt += x;
while (lt <= rt) {
mid = (lt + rt) / 2;
int cnt = count(mid, arr);
if (cnt <= M) {
rt--;
if (mid < answer) {
answer = mid;
}
} else if (cnt > M) {
lt = mid + 1;
} else if (cnt < M) {
rt = mid - 1;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
int N = kb.nextInt();
int M = kb.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++)
arr[i] = kb.nextInt();
System.out.print(T.solution(N, M, arr));
kb.close();
}
}
import java.util.*;
class Main {
public int count(int[] arr, int capacity) {
int cnt = 1, sum = 0;
for (int x : arr) {
if (sum + x > capacity) {
cnt++;
sum = x;
} else
sum += x;
}
return cnt;
}
public int solution(int N, int M, int[] arr) {
int answer = 0;
int lt = Arrays.stream(arr).max().getAsInt();
int rt = Arrays.stream(arr).sum();
while (lt <= rt) {
int mid = (lt + rt) / 2;
if (count(arr, mid) <= M) {
answer = mid;
rt = mid - 1;
} else
lt = mid + 1;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
int N = kb.nextInt();
int M = kb.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++)
arr[i] = kb.nextInt();
System.out.print(T.solution(N, M, arr));
kb.close();
}
}
stream 사용법 기억해두기
int lt = Arrays.stream(arr).max().getAsInt();
int rt = Arrays.stream(arr).sum();
'알고리즘 > JAVA' 카테고리의 다른 글
Recursive, Tree, Graph(DFS, BFS 기초) (0) | 2021.09.26 |
---|---|
10. 마구간 정하기(결정알고리즘) (0) | 2021.09.25 |
8. 이분검색 (0) | 2021.09.25 |
7. 좌표 정렬 (0) | 2021.09.25 |
6. 장난꾸러기 (0) | 2021.09.25 |
댓글