LC 1687. Delivering Boxes from Storage to Ports (dp+slide window)
class Solution {
public:
int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) {
int n=boxes.size();
vector<int> dp(n);
int left=0;
int right=1;
int diff=1;
int curW=boxes[0][1];
dp[0]=2;
while(right<n){
if(boxes[right][0]!=boxes[right-1][0]) diff++;
curW+=boxes[right][1];
while(left<right && (right-left+1>maxBoxes || curW>maxWeight || (left>0 && dp[left]==dp[left-1]))){
curW-=boxes[left][1];
if(boxes[left][0]!=boxes[left+1][0]) diff--;
left++;
}
dp[right]= left==0? diff+1 : dp[left-1]+diff+1;
right++;
}
return dp[n-1];
}
};
ref from zerotrac
class Solution {
public:
int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) {
int n=boxes.size();
vector<int> diff(n);
for(int i=1;i<n;i++){
diff[i]=diff[i-1]+(boxes[i][0]!=boxes[i-1][0]);
}
vector<int> dp(n,INT_MAX);
vector<int> f(n);
deque<int> dq;
vector<long long> wsum(n+1);
for(int i=1;i<=n;i++) wsum[i]=wsum[i-1]+boxes[i-1][1];
for(int i=0;i<n;i++){
while(!dq.empty() && (i-dq.front()>maxBoxes || wsum[i+1]-wsum[dq.front()+1]>maxWeight)) dq.pop_front();
if(i+1<=maxBoxes && wsum[i+1]<=maxWeight) dp[i]=diff[i]+2;
if(!dq.empty()){
dp[i]=min(dp[i],f[dq.front()]+diff[i]+2);
}
f[i]=dp[i]- (i<n-1? diff[i+1]:0);
while(!dq.empty() && f[dq.back()]>=f[i]){
dq.pop_back();
}
dq.push_back(i);
}
return dp[n-1];
}
};