Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit34525e4

Browse files
1029 Two City Scheduling.py
1 parent280deef commit34525e4

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

‎1029 Two City Scheduling.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/python3
2+
"""
3+
There are 2N people a company is planning to interview. The cost of flying the
4+
i-th person to city A is costs[i][0], and the cost of flying the i-th person to
5+
city B is costs[i][1].
6+
7+
Return the minimum cost to fly every person to a city such that exactly N people
8+
arrive in each city.
9+
10+
11+
12+
Example 1:
13+
14+
Input: [[10,20],[30,200],[400,50],[30,20]]
15+
Output: 110
16+
Explanation:
17+
The first person goes to city A for a cost of 10.
18+
The second person goes to city A for a cost of 30.
19+
The third person goes to city B for a cost of 50.
20+
The fourth person goes to city B for a cost of 20.
21+
22+
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people
23+
interviewing in each city.
24+
25+
Note:
26+
27+
1 <= costs.length <= 100
28+
It is guaranteed that costs.length is even.
29+
1 <= costs[i][0], costs[i][1] <= 1000
30+
"""
31+
32+
33+
classSolution:
34+
deftwoCitySchedCost(self,costs:List[List[int]])->int:
35+
"""
36+
sort by city A and greedy? [30, 20]?
37+
sort by total?
38+
sort by diff - either choose A or B, the difference matters
39+
40+
a - b: incremental cost of flying A instead of B
41+
"""
42+
A= [(a-b,a,b)fora,bincosts]
43+
A.sort()
44+
ret=0
45+
remain=len(A)//2
46+
for_,a,binA:
47+
ifremain>0:
48+
ret+=a
49+
remain-=1
50+
else:
51+
ret+=b
52+
53+
returnret
54+
55+
deftwoCitySchedCost_error(self,costs:List[List[int]])->int:
56+
"""
57+
sort by city A and greedy? [30, 20]?
58+
sort by total?
59+
sort by diff - either choose A or B, the difference matters
60+
61+
Error in the abs of difference
62+
"""
63+
A= [(abs(a-b),a,b)fora,bincosts]
64+
A.sort(reverse=True)
65+
ret=0
66+
remain=len(A)//2
67+
for_,a,binA:
68+
ifa>b:
69+
ret+=b
70+
elifremain>0:
71+
ret+=a
72+
remain-=1
73+
else:
74+
ret+=b
75+
76+
returnret

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp