1687. Delivering Boxes from Storage to Ports class Solution: def boxDelivering(self, A: List[List[int]], portsCount: int, B: int, W: int) -> int: n = len(A) need = j = lastj = 0 dp = [0] + [float('inf')] * n for i in range(n): while j < n and B > 0 and W >= A[j][1]: B -= 1 W -= A[j][1] if j == 0 or A[j][0] != A[j - 1][0]: lastj = j need += 1 j += 1 dp[j] = min(dp[j], dp[i] + need + 1) dp[lastj] = min(dp[lastj], dp[i] + need) B += 1 W += A[i][1] if i == n - 1 or A[i][0] != A[i + 1][0]: need -= 1 return dp[-1]