-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-operations-to-make-array-parity-alternating.py
More file actions
58 lines (53 loc) · 1.63 KB
/
minimum-operations-to-make-array-parity-alternating.py
File metadata and controls
58 lines (53 loc) · 1.63 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
46
47
48
49
50
51
52
53
54
55
56
57
58
# Time: O(n)
# Space: O(1)
# greedy
class Solution(object):
def makeParityAlternating(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
POS_INF = float("inf")
NEG_INF = float("-inf")
def count(target):
cnt = 0
mn, mx = POS_INF, NEG_INF
for i, x in enumerate(nums):
if (x%2) == (i%2)^target:
mn = min(mn, x)
mx = max(mx, x)
else:
cnt += 1
mn = min(mn, x+1)
mx = max(mx, x-1)
return [cnt, 0 if len(nums) == 1 else 1 if max(nums) == min(nums) else mx-mn]
return min(count(0), count(1))
# Time: O(n)
# Space: O(1)
# greedy
class Solution2(object):
def makeParityAlternating(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
POS_INF = float("inf")
NEG_INF = float("-inf")
def count(target):
cnt = 0
mn, mx = min(nums), max(nums)
mn2, mx2 = POS_INF, NEG_INF
for i, x in enumerate(nums):
if (x%2) == (i%2)^target:
mn2 = min(mn2, x)
mx2 = max(mx2, x)
else:
cnt += 1
if x == mn:
mn2 = min(mn2, x+1)
mx2 = max(mx2, x+1)
elif x == mx:
mn2 = min(mn2, x-1)
mx2 = max(mx2, x-1)
return [cnt, mx2-mn2]
return min(count(0), count(1))