Make K-Subarray Sums Equal — LeetCode 2607 Python Solution
MediumGreedyArrayMathNumber TheorySorting
- Problem
- #2607
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array arr and an integer k. The array arr is circular.
Example
- Input
- arr = [1,4,1,3], k = 2
- Output
- 1
- Explanation
- we can do one operation on index 1 to make its value equal to 3.
Python solution
Python
class Solution:
def makeSubKSumEqual(self, arr: List[int], k: int) -> int:
n = len(arr)
g = gcd(n, k)
ans = 0
for i in range(g):
t = sorted(arr[i:n:g])
mid = t[len(t) >> 1]
ans += sum(abs(x - mid) for x in t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2607. Make K-Subarray Sums Equal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2607. Make K-Subarray Sums Equal?
- LeetCode 2607. Make K-Subarray Sums Equal is rated Medium on LeetCode.
- What topics does LeetCode 2607. Make K-Subarray Sums Equal cover?
- LeetCode 2607. Make K-Subarray Sums Equal is tagged Greedy, Array, Math, Number Theory and Sorting on LeetCode.