package com.company;
import java.util.*;
class Solution {
public int minDays(int[] bloomDay, int m, int k) {
// 如果 花不够,则直接返回 -1
if (m * k > bloomDay.length){
return -1;
}
int left = Arrays.stream(bloomDay).min().getAsInt();
int right = Arrays.stream(bloomDay).max().getAsInt();
while (left < right){
int mid = (right + left) / 2;
if (getDay(bloomDay, mid, m, k)){
right = mid;
}else {
left = mid + 1;
}
}
return left;
}
private boolean getDay(int[] bloomDay, int mid, int m, int k) {
int sum = 0; // 制作好的花个数
List<Integer> list = new ArrayList<>(); // 记录是否相邻K的花
for (int x : bloomDay) {
if (x <= mid){
list.add(x);
if (list.size() == k){
sum++;
list = new ArrayList<>();
}
}else {
list = new ArrayList<>();
if (sum > m) sum = 0; // 考虑 k=1的情况 单独的花
}
}
// 如果够数,则返回true
if (sum == m) return true;
return false;
}
}
public class Test {
public static void main(String[] args) {
int[] arr = {1,10,3,9,12,10,4,5,7,3,2};
int m = 3;
int k = 2;
System.out.println(new Solution().minDays(arr, m, k)); // 输出 9
int[] arr1 = {1,10,3,10,2};
int m1 = 3;
int k1 = 1;
System.out.println(new Solution().minDays(arr1, m1, k1)); // 输出 3
}
}