-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-cost-for-cutting-cake-ii.py
51 lines (47 loc) · 1.46 KB
/
minimum-cost-for-cutting-cake-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Time: O(mlogm + nlogn)
# Space: O(1)
# sort, greedy
class Solution(object):
def minimumCost(self, m, n, horizontalCut, verticalCut):
"""
:type m: int
:type n: int
:type horizontalCut: List[int]
:type verticalCut: List[int]
:rtype: int
"""
horizontalCut.sort()
verticalCut.sort()
result = 0
cnt_h = cnt_v = 1
while horizontalCut or verticalCut:
if not verticalCut or (horizontalCut and horizontalCut[-1] > verticalCut[-1]):
result += horizontalCut.pop()*cnt_h
cnt_v += 1
else:
result += verticalCut.pop()*cnt_v
cnt_h += 1
return result
# Time: O(mlogm + nlogn)
# Space: O(1)
# sort, greedy
class Solution2(object):
def minimumCost(self, m, n, horizontalCut, verticalCut):
"""
:type m: int
:type n: int
:type horizontalCut: List[int]
:type verticalCut: List[int]
:rtype: int
"""
horizontalCut.sort(reverse=True)
verticalCut.sort(reverse=True)
result = i = j = 0
while i < len(horizontalCut) or j < len(verticalCut):
if j == len(verticalCut) or (i < len(horizontalCut) and horizontalCut[i] > verticalCut[j]):
result += horizontalCut[i]*(j+1)
i += 1
else:
result += verticalCut[j]*(i+1)
j += 1
return result