---
# System prepended metadata

title: 1011. Capacity To Ship Packages Within D Days
tags: [Leetcode, Binary Search, Medium]

---

# 1011. Capacity To Ship Packages Within D Days
###### tags: `Leetcode` `Medium` `Binary Search`
Link: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
## 思路
binary search 找答案
最开始的范围中 最小值是weights里面最大的数字 最大值是weights sum
## Code
```java=
class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int start = 0;
        int end = 0;
        for(int i = 0;i < weights.length;i++){
            start = Math.max(start, weights[i]);
            end += weights[i];
        }
        while(start<end){
            int mid = (start+end)/2;
            if(check(weights, mid) <= days){
                end = mid;
            }
            else{
                start = mid+1;
            }
        }
        return start;
    }
    public int check(int[] weights, int capacity){
        int day = 1;
        int idx = 0;
        int sum = 0;
        while(idx < weights.length){
            if(sum+weights[idx]<=capacity){
                sum+=weights[idx];
                idx++;
            }
            else{
                day+=1;
                sum=weights[idx];
                idx++;
            }
        }
        return day;
    }
}
```
