#3638
Maximum Balanced Shipments
MediumArrayDynamic ProgrammingStackGreedyMonotonic StackDynamic ProgrammingMonotonic Stack
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a monotonic stack to efficiently track the nearest larger parcel weight, allowing us to calculate balanced shipments in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a stack to track indices of parcels and a dp array to store the maximum shipments up to each index.
- 2Step 2: For each parcel, use the stack to find the nearest previous index with a larger weight.
- 3Step 3: Update dp based on the found index and maintain a best array to track the maximum shipments.
solution.py13 lines
1def maxBalancedShipments(weight):
2 n = len(weight)
3 dp = [0] * n
4 best = [0] * n
5 stack = []
6 for i in range(n):
7 while stack and weight[stack[-1]] <= weight[i]:
8 stack.pop()
9 j = stack[-1] if stack else -1
10 dp[i] = (dp[j] + 1) if j != -1 else 1
11 best[i] = max(best[i-1], dp[i])
12 stack.append(i)
13 return best[-1]ℹ
Complexity note: We traverse the array once, and each index is pushed and popped from the stack at most once.
- 1Use of monotonic stack for efficient index tracking
- 2Dynamic programming to store optimal solutions
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.