Skip to content

Commit 9a05fa8

Browse files
authored
Update minimum-cost-for-cutting-cake-ii.py
1 parent 59af8d0 commit 9a05fa8

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Python/minimum-cost-for-cutting-cake-ii.py

+25
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,28 @@ def minimumCost(self, m, n, horizontalCut, verticalCut):
2424
cnt_h += 1
2525
return result
2626

27+
28+
# Time: O(mlogm + nlogn)
29+
# Space: O(1)
30+
# sort, greedy
31+
class Solution2(object):
32+
def minimumCost(self, m, n, horizontalCut, verticalCut):
33+
"""
34+
:type m: int
35+
:type n: int
36+
:type horizontalCut: List[int]
37+
:type verticalCut: List[int]
38+
:rtype: int
39+
"""
40+
horizontalCut.sort(reverse=True)
41+
verticalCut.sort(reverse=True)
42+
result = i = j = 0
43+
while i < len(horizontalCut) or j < len(verticalCut):
44+
if j == len(verticalCut) or (i < len(horizontalCut) and horizontalCut[i] > verticalCut[j]):
45+
result += horizontalCut[i]*(j+1)
46+
i += 1
47+
else:
48+
result += verticalCut[j]*(i+1)
49+
j += 1
50+
return result
51+

0 commit comments

Comments
 (0)