1. Linear Capacity Increment
Intuition
Start cap at max(weights). For each cap, simulate greedy packing. Return the first cap where daysNeeded <= days.
When to apply: Basic baseline check.
Algorithm
- Step 1: low = max(weights), high = sum(weights).
- Step 2: Loop cap from low to high.
- Step 3: Simulate packing: count daysNeeded.
- Step 4: If daysNeeded <= days, return cap.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int shipWithinDays(vector<int>& weights, int days) { int maxW = 0, sumW = 0; for (int w : weights) { maxW = max(maxW, w); sumW += w; } for (int cap = maxW; cap <= sumW; ++cap) { int daysNeeded = 1, current = 0; for (int w : weights) { if (current + w > cap) { daysNeeded++; current = 0; } current += w; } if (daysNeeded <= days) return cap; } return sumW; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * (sum(weights) - max(weights)))— Tests up to 500 * 50000 = 2.5 * 107 capacities with O(n) simulation each, causing TLE. - Space complexity:
O(1)— O(1) auxiliary space.