Leetcode June challenge ( Two City Scheduling )

In time, you will call me master -- Star Wars

Week 1 Two City Scheduling

greedy
http://img2.58codes.com/2024/20116751HfjFDrV3iI.png

description :

Given fee to go to City A cost[i][0]Given fee to go to City B cost[i][1]Calculate minimum fee to fly every person to a city such that exactly N people arrive in each city

Solution :

class Solution:  def twoCitySchedCost(self, costs: List[List[int]]) -> int:      diff_cost = list()      total_cost = 0      for i in range(0, len(costs)):          diff_cost.append(costs[i][1] - costs[i][0])          total_cost += costs[i][0]      diff_cost = sorted(diff_cost)      for i in range(0, len(costs)//2):          total_cost += diff_cost[i]      return total_cost

Solution detail :

suppose every person goes to City ACalculate the difference between City A & City Bif difference is large means we have to increase budgetsort the difference between two citieschoose N//2 cities for people in City A to City B

中文版:

给定 2D array 包含去 城市A (cost[i][0] ) & 城市B (cost[i][1] ) 费用计算最少费用并且 城市A & 城市B 人数要相等假设一开始所有人都在城市A,计算出从城市A移到城市B的差额费用排序并选出由小到大的 N//2 人数 移到城市B也就是 sum(所有人在城市A) + (移到城市Bcost)

Person | City A cost | City B cost | move fee City B | sort
-------|-------------|-------------|-----------------------|
0 | 10 | 20 | 10 | -350
1 | 30 | 200 | 170 | -10
2 | 400 | 50 | -350 | 10
3 | 30 | 20 | -10 | 170

result : 10 + 30 + 400 + 30 -350 - 10 = 110


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章