Skip to content

Commit ecd739c

Browse files
committed
1014 added.
1 parent 40ed4f5 commit ecd739c

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
cmake_minimum_required(VERSION 3.13)
2+
project(C)
3+
4+
set(CMAKE_CXX_STANDARD 14)
5+
6+
add_executable(C main.cpp)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/// Source : https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
2+
/// Author : liuyubobobo
3+
/// Time : 2019-03-16
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <numeric>
8+
9+
using namespace std;
10+
11+
12+
/// Binary Search
13+
/// Time Complexity: O(nlog(sum(weights)))
14+
/// Space Complexity: O(1)
15+
class Solution {
16+
public:
17+
int shipWithinDays(vector<int>& weights, int D) {
18+
19+
int l = *max_element(weights.begin(), weights.end()),
20+
r = accumulate(weights.begin(), weights.end(), 0);
21+
while(l < r){
22+
// cout << "check " << l << " " << r << endl;
23+
int mid = (l + r) / 2;
24+
if(ok(weights, mid, D))
25+
r = mid;
26+
else
27+
l = mid + 1;
28+
}
29+
return l;
30+
}
31+
32+
private:
33+
bool ok(const vector<int>& weights, int C, int D){
34+
35+
int d = 0, cur = 0;
36+
for(int w: weights)
37+
if(cur + w <= C) cur += w;
38+
else d ++, cur = w;
39+
if(cur) d ++;
40+
return d <= D;
41+
}
42+
};
43+
44+
45+
int main() {
46+
47+
vector<int> weight1 = {1,2,3,4,5,6,7,8,9,10};
48+
cout << Solution().shipWithinDays(weight1, 5) << endl;
49+
// 15
50+
51+
vector<int> weight2 = {1,2,3,1,1};
52+
cout << Solution().shipWithinDays(weight2, 4) << endl;
53+
// 3
54+
55+
return 0;
56+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,4 +681,5 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
681681
| | | | | | |
682682
| 1012 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | [] | [C++](1012-Complement-of-Base-10-Integer/cpp-1012/) | | |
683683
| 1013 | [Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/) | [] | [C++](1013-Pairs-of-Songs-With-Total-Durations-Divisible-by-60/cpp-1013/) | | |
684+
| 1014 | [Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) | [] | [C++](1014-Capacity-To-Ship-Packages-Within-D-Days/cpp-1014/) | | |
684685
| | | | | | |

0 commit comments

Comments
 (0)