Skip to content

Commit 6e9c58f

Browse files
authored
Create make-k-subarray-sums-equal.py
1 parent d81f987 commit 6e9c58f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Python/make-k-subarray-sums-equal.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
import random
5+
6+
7+
# math, greedy, quick select
8+
class Solution(object):
9+
def makeSubKSumEqual(self, arr, k):
10+
"""
11+
:type arr: List[int]
12+
:type k: int
13+
:rtype: int
14+
"""
15+
def gcd(a, b):
16+
while b:
17+
a, b = b, a%b
18+
return a
19+
20+
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
21+
def tri_partition(nums, left, right, target, compare):
22+
mid = left
23+
while mid <= right:
24+
if nums[mid] == target:
25+
mid += 1
26+
elif compare(nums[mid], target):
27+
nums[left], nums[mid] = nums[mid], nums[left]
28+
left += 1
29+
mid += 1
30+
else:
31+
nums[mid], nums[right] = nums[right], nums[mid]
32+
right -= 1
33+
return left, right
34+
35+
right = len(nums)-1
36+
while left <= right:
37+
pivot_idx = random.randint(left, right)
38+
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
39+
if pivot_left <= n <= pivot_right:
40+
return
41+
elif pivot_left > n:
42+
right = pivot_left-1
43+
else: # pivot_right < n.
44+
left = pivot_right+1
45+
46+
l = gcd(k, len(arr))
47+
result = 0
48+
for i in xrange(l):
49+
vals = [arr[j] for j in xrange(i, len(arr), l)]
50+
nth_element(vals, len(vals)//2)
51+
result += sum(abs(v-vals[len(vals)//2]) for v in vals)
52+
return result

0 commit comments

Comments
 (0)