Skip to content

Commit 5807fc8

Browse files
committed
Add solution
1 parent cbd96d3 commit 5807fc8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 3638. Maximum Balanced Shipments
2+
// You are given an integer array weight of length n, representing the weights of n parcels arranged in a straight line. A shipment is defined as a contiguous subarray of parcels. A shipment is considered balanced if the weight of the last parcel is strictly less than the maximum weight among all parcels in that shipment.
3+
// Select a set of non-overlapping, contiguous, balanced shipments such that each parcel appears in at most one shipment (parcels may remain unshipped).
4+
// Return the maximum possible number of balanced shipments that can be formed.
5+
6+
7+
// Solution: Greedy
8+
9+
// Once we find a valid subarray, it is optimal to take that as a shipment instead of extending it.
10+
// Extending a subarray can only make it worse by having a max element as the last element.
11+
12+
// There is also no benefit to skipping over any elements, because
13+
// if we skip over a large number, it can help create a valid subarray being the maximum
14+
// if we skip over a small number, it won't make any different since it's not the maximum anyway
15+
16+
// Time Complexity: O(n) 9ms
17+
// Space Complexity: O(1) 72MB
18+
function maxBalancedShipments(weight) {
19+
let balanced = 0, max = 0;
20+
for (let w of weight) {
21+
max = Math.max(max, w);
22+
if (w < max) {
23+
balanced++;
24+
max = 0;
25+
}
26+
}
27+
return balanced;
28+
};
29+
30+
// Two test cases
31+
console.log(maxBalancedShipments([2,5,1,4,3])) // 2
32+
console.log(maxBalancedShipments([4,4])) // 0

0 commit comments

Comments
 (0)