Skip to content

Commit 658ae5a

Browse files
authored
Create allocate-mailboxes.py
1 parent 513b3f3 commit 658ae5a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Python/allocate-mailboxes.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Time: O(m * n^2)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def minDistance(self, houses, k):
6+
"""
7+
:type houses: List[int]
8+
:type k: int
9+
:rtype: int
10+
"""
11+
def cost(prefix, i, j):
12+
return (prefix[j+1]-prefix[(i+j+1)//2])-(prefix[(i+j)//2+1]-prefix[i])
13+
14+
houses.sort()
15+
prefix = [0]*(len(houses)+1)
16+
for i, h in enumerate(houses):
17+
prefix[i+1] = prefix[i]+h
18+
dp = [cost(prefix, 0, j) for j in xrange(len(houses))]
19+
for m in xrange(1, k):
20+
for j in reversed(xrange(m, len(houses))):
21+
for i in xrange(m, j+1):
22+
dp[j] = min(dp[j], dp[i-1]+cost(prefix, i, j))
23+
return dp[-1]

0 commit comments

Comments
 (0)