-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-cost-to-make-two-binary-strings-equal.py
More file actions
45 lines (42 loc) · 1.25 KB
/
minimum-cost-to-make-two-binary-strings-equal.py
File metadata and controls
45 lines (42 loc) · 1.25 KB
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
# Time: O(n)
# Space: O(1)
# math
class Solution(object):
def minimumCost(self, s, t, flipCost, swapCost, crossCost):
"""
:type s: str
:type t: str
:type flipCost: int
:type swapCost: int
:type crossCost: int
:rtype: int
"""
cnt = [0]*2
for i in xrange(len(s)):
if s[i] == t[i]:
continue
cnt[ord(s[i])-ord('0')] += 1
mn, mx = min(cnt[0], cnt[1]), max(cnt[0], cnt[1])
q, r = divmod(mx-mn, 2)
return mn*min(swapCost, 2*flipCost)+q*min(crossCost+swapCost, 2*flipCost)+r*flipCost
# Time: O(n)
# Space: O(1)
# math
class Solution2(object):
def minimumCost(self, s, t, flipCost, swapCost, crossCost):
"""
:type s: str
:type t: str
:type flipCost: int
:type swapCost: int
:type crossCost: int
:rtype: int
"""
cnt = [0]*2
for i in xrange(len(s)):
if s[i] == t[i]:
continue
cnt[ord(s[i])-ord('0')] += 1
mn, mx = min(cnt[0], cnt[1]), max(cnt[0], cnt[1])
q, r = divmod(mx-mn, 2)
return min((mx+mn)*flipCost, mn*swapCost+(mx-mn)*flipCost, mn*swapCost+q*(crossCost+swapCost)+r*flipCost)