1295. Three-Shelf Closest Trio
A shop keeps three shelves of items priced in whole currency units. The arrays a, b and c give the prices on each shelf, each already sorted in non-decreasing order. A shopper takes exactly one item from every shelf and wants the three prices to be as close together as possible. Return the smallest possible difference between the most expensive and the cheapest of the three chosen prices. A shelf may contain repeated prices.
Aim for O(a + b + c) time and O(1) extra space, using the lengths of the three arrays: keep one pointer per shelf, record the current spread, and always advance the pointer that sits on the smallest price.
Example 1
- Input:
- a = [1,4,10], b = [2,15,20], c = [10,12]
- Output:
- 5
- Explanation:
Picking 10, 15 and 12 gives a spread of 15 - 10 = 5, and no other trio has a smaller spread.
Example 2
- Input:
- a = [5], b = [5], c = [5]
- Output:
- 0
- Explanation:
Each shelf has a single price, 5, so the three prices are equal and the spread is 0.
Example 3
- Input:
- a = [1,2,3], b = [10,20,30], c = [100,200,300]
- Output:
- 97
- Explanation:
Every price on the first shelf is at most 3 and every price on the third is at least 100; taking 3, 10 and 100 gives 97, the smallest spread.
Constraints
1 ≤ a.length, b.length, c.length ≤ 1000
0 ≤ a[i], b[i], c[i] ≤ 109
each array is sorted non-decreasing
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(a + b + c)
- Space
- O(1)