← Home

1011. Capacity To Ship Packages Within D Days

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
101

The trick here is to name the state correctly, then let the implementation follow. For 1011. Capacity To Ship Packages Within D Days, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are possible, shipWithinDays.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 52 ms, faster than 67.73% of C++ online submissions for Capacity To Ship Packages Within D Days.
02//Memory Usage: 12.3 MB, less than 11.11% of C++ online submissions for Capacity To Ship Packages Within D Days.
03class Solution {
04public:
05    vector<int> weights;
06    int D;
07    
08    bool possible(int C){
09        int days = 0;
10        int i = 0; //next day starts from here
11        
12        while(i < weights.size()){
13            int cap = 0;
14            while(i < weights.size() && cap + weights[i] <= C){
15                cap += weights[i++];
16            }
17            days++;
18        }
19        
20        return days <= D;
21    };
22    
23    int shipWithinDays(vector<int>& weights, int D) {
24        this->weights = weights;
25        this->D = D;
26        
27        //the capcacity must >= max weight of a goods
28        int l = *max_element(weights.begin(), weights.end());
29        //we can ship in 1 day
30        int r = accumulate(weights.begin(), weights.end(), 0);
31        int mid;
32        
33        while(l <= r){
34            mid = (l + r)/2;
35            // cout << l << " " << mid << " " << r << " " << possible(mid) << endl;
36            if(possible(mid)){
37                if(mid == l) return mid;
38                r = mid;
39            }else{
40                //mid is not valid, increase the lower bound
41                l = mid+1;
42            }
43            
44        }
45        
46        return mid;
47    }
48};
49
50//some modification from
51//https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/256729/JavaC%2B%2BPython-Binary-Search
52//Runtime: 52 ms, faster than 67.73% of C++ online submissions for Capacity To Ship Packages Within D Days.
53//Memory Usage: 12.3 MB, less than 11.11% of C++ online submissions for Capacity To Ship Packages Within D Days.
54class Solution {
55public:
56    vector<int> weights;
57    int D;
58    
59    bool possible(int C){
60        int days = 0;
61        int i = 0; //next day starts from here
62        
63        while(i < weights.size()){
64            int cap = 0;
65            while(i < weights.size() && cap + weights[i] <= C){
66                cap += weights[i++];
67            }
68            days++;
69        }
70        
71        return days <= D;
72    };
73    
74    int shipWithinDays(vector<int>& weights, int D) {
75        this->weights = weights;
76        this->D = D;
77        
78        //the capcacity must >= max weight of a goods
79        int l = *max_element(weights.begin(), weights.end());
80        //we can ship in 1 day
81        int r = accumulate(weights.begin(), weights.end(), 0);
82        int mid;
83        
84        while(l < r){
85            mid = (l + r)/2;
86            // cout << l << " " << mid << " " << r << " " << possible(mid) << endl;
87            if(possible(mid)){
88                r = mid;
89            }else{
90                //mid is not valid, increase the lower bound
91                l = mid+1;
92            }
93        }
94        
95        //the loop ends at l == r, so now l is the only valid value
96        return l;
97    }
98};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.