题解 | #画匠问题#
画匠问题
http://www.nowcoder.com/practice/767778ca5b38446cba801820df11399d
import java.util.Scanner; public class Main { public static int getNeedNum(int[] arr, long lim) { int res = 1; long stepSum = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > lim) { return Integer.MAX_VALUE; } stepSum += arr[i]; if (stepSum > lim) { res++; stepSum = arr[i]; } } return res; } public static long solution3(int[]arr,int num){ if(arr==null||arr.length==0||num<1){ throw new RuntimeException("err"); } if(arr.length<num){ int max=Integer.MIN_VALUE; for (int i = 0; i < arr.length ; i++) { max=Math.max(max,arr[i]); } return max; }else { long minSum=0; long maxSum=0; for (int i = 0; i < arr.length ; i++) { maxSum+=arr[i]; } //最终目标,num>=需要的num while (minSum!=maxSum-1){ long mid=(maxSum+minSum)/2; //员工的限制时间 if(getNeedNum(arr,mid)>num){ minSum=mid; }else { maxSum=mid; } } return maxSum; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k=in.nextInt(); int[]arr=new int[n]; for (int i = 0; i <n ; i++) { arr[i]=in.nextInt(); } System.out.println(solution3(arr,k)); } }