Skip to content

Commit a1d8a78

Browse files
authored
Create delivering-boxes-from-storage-to-ports.cpp
1 parent 0f59579 commit a1d8a78

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) {
7+
vector<int> dp(size(boxes) + 1);
8+
int left = 0, cost = 1, curr = 0;
9+
for (int right = 0; right < size(boxes); ++right) {
10+
if (right == 0 || boxes[right][0] != boxes[right - 1][0]) {
11+
++cost;
12+
}
13+
curr += boxes[right][1];
14+
while (right - left + 1 > maxBoxes ||
15+
curr > maxWeight ||
16+
(left + 1 < right + 1 && dp[left + 1] == dp[left])) {
17+
curr -= boxes[left][1];
18+
if (boxes[left + 1][0] != boxes[left][0]) {
19+
--cost;
20+
}
21+
++left;
22+
}
23+
dp[right + 1] = dp[(left - 1) + 1] + cost;
24+
}
25+
return dp[size(boxes)];
26+
}
27+
};

0 commit comments

Comments
 (0)