KatInterview

Budget-Constrained Round-Trip Selection

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsgreedysortingarrays

Last updated

Tests greedy selection and sorting to maximize items within a budget while minimizing cost for that maximum count.

You are planning round-trip visits starting from your base at position 0 on a one-dimensional number line. You have a list of destinations (integers representing positions) and a travel budget (maximum total distance you can cover).

Each destination requires a separate round trip from position 0 to that destination and back. The cost of visiting a destination at position x is 2 * |x| (the round-trip distance). Duplicate positions in the input list represent the same destination and are only visited once.

Your goal is to:

  1. Maximize the number of distinct destinations you visit
  2. Minimize the total distance traveled to achieve that maximum number of visits

Return a list [count, distance] where count is the maximum number of destinations you can visit within the budget, and distance is the minimum total distance required to visit that many destinations.

Constraints

  • 1 ≤ length of destinations ≤ 10^5
  • -10^6 ≤ each destination value ≤ 10^6
  • 0 ≤ budget ≤ 10^9
  • If no destinations can be visited within the budget, return [0, 0]
  • Position 0 (if present in the list) costs nothing to visit

Examples

Example 1

Input: budget_constrained_trips([2, -3, 5, -1], 10)

Output: [2, 6]

Example 2

Input: budget_constrained_trips([10, 20], 15)

Output: [0, 0]

Hints

Hint 1

Consider what strategy maximizes the number of locations you can afford to visit

Hint 2

Each location has an independent cost. Which locations should you prioritize?

Hint 3

Sort the costs and take locations greedily while staying within budget