Skip to content

Commit 9fa07d8

Browse files
authored
Create minimum-array-changes-to-make-differences-equal.py
1 parent 6944326 commit 9fa07d8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n + k)
2+
# Space: O(k)
3+
4+
# prefix sum, difference array
5+
class Solution(object):
6+
def minChanges(self, nums, k):
7+
"""
8+
:type nums: List[int]
9+
:type k: int
10+
:rtype: int
11+
"""
12+
diff = [0]*((k+1)+1)
13+
def update(left, right, d):
14+
diff[left] += d
15+
diff[right+1] -= d
16+
17+
for i in xrange(len(nums)//2):
18+
curr = abs(nums[i]-nums[~i])
19+
mx = max(nums[i]-0, k-nums[i], nums[~i]-0, k-nums[~i])
20+
# 1 change for i in range(0, curr)
21+
update(0, curr-1, 1)
22+
# 1 change for i in range(curr+1, mx+1)
23+
update(curr+1, mx, 1)
24+
# 2 changes for i in range(mx+1, k+1)
25+
update(mx+1, k, 2)
26+
result = len(nums)//2
27+
curr = 0
28+
for i in xrange(k+1):
29+
curr += diff[i]
30+
result = min(result, curr)
31+
return result

0 commit comments

Comments
 (0)