1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { public int shipWithinDays(int[] weights, int D) { return binarySearch(0, Integer.MAX_VALUE, weights, D); }
public int binarySearch(int l, int r, int[] weights, int D){ while(l < r){ int mid = l + (r-l)/2; if(isValid(mid, weights, D)){ r = mid; }else{ l = mid + 1; } } return l; }
public boolean isValid(int ans, int[] weights, int D){ int day = 0; int w2 = ans+1; for(int w : weights){ if(ans - w2 >= w){ w2+=w; }else if(w <= ans){ w2 = w; day ++; }else{ return false; } } if(day <= D){ return true; } return false; } }
|