Skip to content

Instantly share code, notes, and snippets.

@phongngtuan
Created February 27, 2020 07:27
Show Gist options
  • Save phongngtuan/bfb52a51a142409dddd57fb39e70c0ab to your computer and use it in GitHub Desktop.
Save phongngtuan/bfb52a51a142409dddd57fb39e70c0ab to your computer and use it in GitHub Desktop.
import heapq
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
heap = []
for cost in costs:
heapq.heappush(heap, (-abs(cost[0] - cost[1]), cost[0], cost[1]))
N = len(costs) / 2
total = 0
a_count = b_count = 0
while len(heap):
next_person = heapq.heappop(heap)
if next_person[1] < next_person[2]:
if a_count < N:
a_count += 1
total += next_person[1]
else:
b_count += 1
total += next_person[2]
else:
if b_count < N:
b_count += 1
total += next_person[2]
else:
a_count += 1
total += next_person[1]
return total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment