Program to find minimum cost to send same number of people to two different cities in Python

Suppose we have a list called costs, where costs[i] has [c1, c2] indicating that for person i it costs c1 amount to reach city 0 and c2 amount to reach city 1. We want the same number of people to go to city 0 as city 1, and we need to find the minimum cost required.

So, if the input is like costs = [[2, 6],[10, 3],[4, 9],[5, 8]], then the output will be 17, because person 0 and 2 will go to city 0 and person 1 and 3 to city 1. For city 0, the cost is 2+4 = 6, and for city 1, the cost is 8+3 = 11, total is 17.

Approach

The key insight is to initially assign everyone to city 0, then strategically move half the people to city 1 based on the cost difference. We follow these steps ?

  • s := 0 (total cost)
  • differences := a new list to store cost differences
  • for each pair (x, y) in costs, do
    • s := s + x (add city 0 cost for everyone initially)
    • insert (y - x) into differences (cost difference between cities)
  • sort the differences list
  • for the first half of differences, add the negative differences to s
  • return s

Example

Let us see the following implementation to get better understanding ?

def solve(costs):
    s = 0
    differences = []
    
    # Initially assign everyone to city 0 and calculate differences
    for city0_cost, city1_cost in costs:
        s += city0_cost
        differences.append(city1_cost - city0_cost)
    
    # Sort differences to find most beneficial moves to city 1
    differences.sort()
    
    # Move half the people to city 1 (choose most beneficial moves)
    for i in range(len(differences) // 2):
        s += differences[i]
    
    return s

costs = [[2, 6],[10, 3],[4, 9],[5, 8]]
print(solve(costs))
17

How It Works

Let's trace through the example step by step ?

costs = [[2, 6],[10, 3],[4, 9],[5, 8]]

# Step 1: Assign everyone to city 0 initially
# s = 2 + 10 + 4 + 5 = 21
# differences = [6-2, 3-10, 9-4, 8-5] = [4, -7, 5, 3]

# Step 2: Sort differences
# differences = [-7, 3, 4, 5]

# Step 3: Move 2 people (half) to city 1 with most beneficial moves
# Choose differences[-7] and differences[3]
# s = 21 + (-7) + 3 = 17

print("Initial cost (everyone to city 0):", 2 + 10 + 4 + 5)
print("Cost differences:", [6-2, 3-10, 9-4, 8-5])
print("Sorted differences:", sorted([6-2, 3-10, 9-4, 8-5]))
print("Final minimum cost:", 17)
Initial cost (everyone to city 0): 21
Cost differences: [4, -7, 5, 3]
Sorted differences: [-7, 3, 4, 5]
Final minimum cost: 17

Conclusion

This greedy algorithm achieves optimal cost distribution by initially assigning everyone to city 0, then moving half the people to city 1 based on the most beneficial cost differences. The time complexity is O(n log n) due to sorting.

Updated on: 2026-03-26T17:16:08+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements