BackhardTwo Pointers

Minimum Conveyor Section for K Target Shipments Solution

Problem Statement

A logistics center processes packages on a conveyor belt represented by an integer array `weights`, where `weights[i]` is the weight of the $i$-th package. To optimize shipping, packages must be grouped into pairs. A pair of packages is considered a "target shipment" if their combined weight is exactly `target`. Both packages in a shipment must be selected from the same contiguous segment of the conveyor belt. Additionally, to ensure processing efficiency, we want to form at least `k` such pairwise disjoint target shipments (meaning no package can belong to more than one shipment). Find and return the minimum length of a contiguous conveyor belt segment (subarray) that contains at least `k` disjoint target shipments. If it is impossible to find such a segment, return `-1`.

Example 1
Input
weights = [1, 5, 4, 3, 5, 2, 3, 4, 1], target = 6, k = 2
Output
5

Explanation: The contiguous subarray from index 2 to 6 is [4, 3, 5, 2, 3]. Within this segment, we can form 2 disjoint target shipments: the package at index 2 (weight 4) with the package at index 5 (weight 2), and the package at index 3 (weight 3) with the package at index 6 (weight 3). The length of this segment is 5. No shorter segment contains at least 2 disjoint shipments.

Example 2
Input
weights = [2, 2, 2, 2], target = 4, k = 2
Output
4

Explanation: To form 2 disjoint shipments of weight 4, we need four packages of weight 2. The shortest segment containing all of them is the entire array of length 4.

Example 3
Input
weights = [1, 2, 3, 4], target = 10, k = 1
Output
-1

Explanation: There are no two packages on the conveyor belt that sum up to 10. Thus, we cannot form even 1 target shipment.

Constraints

  • 1 <= weights.length <= 10^5
  • 1 <= weights[i], target <= 10^9
  • 1 <= k <= weights.length / 2
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free