AMAZON Coding Question – Solved

6 Live
Amazon has multiple delivery centers for the distribution of its goods. In one such center, parcels are arranged in a sequence where the ith parcel has a weight of weight[i]. A shipment is constituted of a contiguous segment of parcels in this arrangement. For example, with weights [3, 6, 3], possible shipments include [3], [6], [3], [3, 6], [6, 3], and [3, 6, 3], but not [3, 3] (since it’s not contiguous). These shipments are to be loaded for delivery and must be **balanced**. A shipment is considered balanced **if the weight of the last parcel in the shipment is *not* the maximum weight** in that shipment. - Example: [3, 9, 4, 7] is balanced because the last parcel is 7 and the max is 9. - [4, 7, 2, 7] is **not** balanced since the last parcel (7) is also the maximum. **Task:** Given an array `weight` of size `n`, representing parcel weights, determine the **maximum number of balanced shipments** that can be formed such that: - Each parcel belongs to exactly one shipment - Each shipment is a contiguous subarray - Each shipment is balanced If no valid balanced shipment can be formed, return 0. **Example:** `weight = [1, 2, 3, 2, 6, 3]` There are n = 6 parcels. The optimal way is to divide them into two shipments: [1, 2, 3, 2] and [6, 3], both of which are balanced. Hence, the output is `2`. **Function Description:** Complete the function `getMaximumBalancedShipments` in the editor below. **Function Signature:** `int getMaximumBalancedShipments(int[] weight)`

Asked in: AMAZON

Image of the Question

Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


def getMaximumBalancedShipments(weight):
    # Write your code here
    answer = 0
    last = None
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
This problem asks us to partition a sequence of parcels (each with a weight) into contiguous shipments such that each shipment is balanced, with the goal of maximizing the number of such shipments. A shipment is balanced if the last parcel in the shipment is NOT the maximum weight within that shipment.

To understand and solve this, let's carefully analyze the problem and approach it step-by-step.

1. **Restate the problem in your own words:**
We have an array of weights and need to split it into contiguous subarrays (shipments). Each shipment must satisfy the balanced condition: the last element in the shipment is not the maximum element in that shipment. Our objective is to create as many such balanced shipments as possible, ensuring each parcel belongs to exactly one shipment.

2. **Key constraints and observations:**
- Each shipment is a contiguous segment of the array.
- Each parcel must be included exactly once (partitions cover the entire array).
- Balanced condition: last parcel ≠ max of shipment.
- If no valid partitioning exists, return 0.
- We want to maximize the count of balanced shipments.

3. **Implications of the balanced condition:**
The shipment’s last parcel is not the maximum means:
- The maximum element must appear somewhere before the last element in the shipment.
- The last element must be strictly less than the maximum element.
- It cannot be equal to the max.
This restricts which shipments can end where.

4. **Understanding shipment boundaries:**
Since the shipment is contiguous, when deciding where to cut the shipment, the cut position is at the boundary between shipments.
For a shipment ending at index `j`, the subarray `[start, j]` must satisfy that `weight[j]` is not the max in `[start, j]`.

5. **How to check balanced condition efficiently for a candidate shipment:**
We want to check if the last element is not the maximum in the subarray.
This means:
- max in `[start, j]` > weight[j]
- Or equivalently, max in `[start, j-1]` ≥ max in `[start, j]` > weight[j]
Since the max might be anywhere in the shipment except at the last position, the max value must be greater than the last element.

6. **Formulating a strategy to find partitions:**
We want to create the maximum number of shipments, so intuitively, we want to make as many cuts as possible, but only where balanced shipments end.
- We iterate over the array from left to right.
- We try to find the earliest possible balanced shipment ending at each position.
- When a balanced shipment ends, we cut and start a new shipment from the next element.

7. **Key challenge - how to efficiently check the balanced condition for many subarrays?**
Naively checking max for each subarray is O(n²), which is too expensive.
We need a way to efficiently track maximums and determine if the last element is less than that max in a growing segment.

8. **Possible data structures or preprocessing to assist:**
- Use prefix maximum arrays to track maximum elements up to each position.
- However, prefix max alone is not enough because the shipment start varies.
- Alternatively, maintain variables as we expand the shipment: track the current max and last element, and check if last element < current max.
- If this condition is met, the current segment is balanced.

9. **Greedy approach to maximize shipments:**
Since the goal is to maximize the number of balanced shipments, a greedy strategy would be:
- Start a new shipment at the first parcel.
- Extend the shipment parcel by parcel.
- At each new parcel, update the current max in the shipment.
- If the last parcel's weight is less than the shipment max, the shipment is balanced, so we can cut here to form a shipment.
- Record this shipment, then start a new shipment from the next parcel.
- If not, continue adding parcels to the current shipment.
This ensures maximal partitioning since we cut at the earliest balanced position.

10. **Why greedy works here:**
- The balanced condition is monotonic: once a shipment is balanced at some endpoint, extending it further won't necessarily make it balanced again at an earlier position.
- Cutting as soon as the balanced condition is met allows maximal number of shipments.

11. **Edge cases to consider:**
- If the last element of the shipment is always the max, then no cut is possible until the entire array ends — return 0.
- All elements equal — no balanced shipments because the last parcel is always the max (ties count as max), so output 0.
- Single element array — shipment of size 1 has last element equal to max, not balanced, return 0.

12. **Algorithm sketch:**
- Initialize count = 0, shipment start at index 0, current max = weight[0].
- Iterate over weights from left to right:
- Update current max as max(current max, weight[i]).
- Check if weight[i] < current max — if yes, this shipment is balanced and can end here.
- Increase count.
- Reset shipment start to i+1 and current max accordingly.
- Otherwise, continue.
- At the end, return count.

13. **Time and space complexity:**
- The approach is linear time O(n) since it scans the array once.
- Uses O(1) additional space besides input.

14. **Summary:**
- The problem boils down to partitioning the array into the maximum number of contiguous subarrays where the last element is strictly less than the max of that subarray.
- A greedy method scanning from left to right and cutting shipments whenever the balanced condition is met yields the maximum count of balanced shipments.
- This method is efficient and works well within the constraints of large inputs.

By approaching the problem with these considerations, focusing on how to identify balanced shipments greedily and maximizing their count, you can design a neat and optimal solution.
```


Related Questions