Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1hashing
A parcel-delivery app scans parcels on a belt, in order. A crate takes exactly two parcels, and it is full when their weights add up to target.
A packer holds the earlier parcel of a pair at a side station until its partner arrives. Planners size the station by the widest gap, counted in belt positions, between the two parcels of any pair that fills a crate.
Write widest_matching_gap(weights, target).
weights[i] is the weight of the i-th parcel on the belt.i < j with weights[i] + weights[j] == target.j - i over all pairs.Input: weights = [8, 3, 5, 2, 7, 3, 5], target = 10
Output: 4Each parcel looks for its partner among the earlier parcels. The map keeps the first position of each weight, and the search goes on to the end.
| Position | Weight | Partner | First position of the partner | Gap | Widest so far |
|---|---|---|---|---|---|
| 0 | 8 | 2 | none | -1 | |
| 1 | 3 | 7 | none | -1 | |
| 2 | 5 | 5 | none | -1 | |
| 3 | 2 | 8 | 0 | 3 | 3 |
| 4 | 7 | 3 | 1 | 3 | 3 |
| 5 | 3 | 7 | 4 | 1 | 3 |
| 6 | 5 | 5 | 2 | 4 | 4 |
The widest pair is the two 5s, at positions 2 and 6.
Input: weights = [4, 9], target = 20
Output: -14 + 9 is 13, so no pair fills a crate.
Input: weights = [6, 6, 6, 6], target = 12
Output: 3Every pair of 6s fills a crate. The widest pair is the first and the last, positions 0 and 3.
1 ≤ weights.length ≤ 100,000 (parcels on one belt)1 ≤ weights[i] ≤ 10^9 (grams)1 ≤ target ≤ 10^9Trying every pair costs about n × n / 2 checks, which is about 5 × 10^9 at n = 100,000. A map that holds each weight's first position finds the best partner for a parcel in one step, so one pass makes about n steps.
Read the values too. target - weight is between -10^9 and 10^9, which fits in a 32-bit int.