 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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] indicates that for person i it costs c1 amount to reach city 0 and costs c2 amount to reach city 1. We want the same number of people to go to city 0 as city 1, we have 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, so for city 0, the cost is 2+4 = 6, and for city 1, the cost is 8+3 = 11, total is 17.
To solve this, we will follow these steps −
- s := 0
- a := a new list
- for each pair (x, y) in costs, do- s := s + x
- insert (y - x) into a at the end
 
- sort the list a
- for i in range 0 to floor of (size of a / 2) - 1, do- s := s + a[i]
 
- return s
Example
Let us see the following implementation to get better understanding −
def solve(costs): s = 0 a = [] for x, y in costs: s += x a += (y - x,) a.sort() for i in range(len(a) // 2): s += a[i] return s costs = [[2, 6],[10, 3],[4, 9],[5, 8]] print(solve(costs))
Input
[[2, 6],[10, 3],[4, 9],[5, 8]]
Output
17
Advertisements
 