Maximize 1D deliveries within distance and minimize total distance
GoogleSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to prioritize objectives using a greedy strategy or sorting to maximize deliveries while minimizing travel cost within a constrained route.
Problem Statement
You are a delivery driver starting at position 0 on a 1D number line. You have a list of delivery locations locations (integers) and a maximum travel distance max_dist.
Each delivery requires you to visit the location and return to 0. Your total distance is the sum of the absolute values of the coordinates you visit, multiplied by 2 (to account for the round trip back to the origin). You want to:
- Maximize the number of unique delivery locations visited.
- Minimize the total distance traveled for that maximum number of deliveries.
Implement the function optimize_deliveries(locations, max_dist) which returns the maximum number of deliveries possible and the minimum total distance required to achieve it.
Function Signature
def optimize_deliveries(locations, max_dist) -> tuple[int, int]
Constraints
locationslength: 1 to 10^5locationsvalues: -10^6 to 10^6max_dist: 0 to 10^9
Examples
Example 1:
Input: locations = [2, -3, 5, -1], max_dist = 10
Output: (3, 8)
Explanation: We can pick locations [2, -1, -3]. Total distance: 22 + 12 + 3*2 = 12 (too high). We pick the three closest locations: [-1, 2, -3]. The furthest is 3. Total distance = 3 * 2 = 6.
Example 2:
Input: locations = [10, 20], max_dist = 15
Output: (1, 20)
Explanation: Only one location (10) can be reached since 210 = 20 > 15 (Wait, 210=20 > 15 is false, so we can visit 10).
Hints
Hint 1
Since every delivery requires a return to the origin, the cost of visiting any set of locations is simply twice the absolute value of the furthest location in that set.
Hint 2
Sort the absolute values of the locations in ascending order to easily pick the closest points.
Hint 3
The maximum number of deliveries is determined by how many of the smallest absolute values you can fit such that the furthest one, multiplied by 2, is within `max_dist`.
Follow-up questions
- How would the solution change if you do not have to return to the origin after the final delivery?
- What if you have a vehicle capacity constraint where you can only carry 'k' packages at a time, requiring multiple trips to the origin?
- How would you optimize the solution if the input `locations` was a stream of data rather than a fixed list?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.