from collections import Counter
def add(v, s, t, sum_values, k):
# If the size of set s is less than k - 1, add the element directly to s
if len(s) < k - 1:
s[v] += 1
sum_values[0] += v
return
# If the element is greater than or equal to the maximum element in s, add it to t
if v >= max(s):
t[v] += 1
return
# If the element is smaller than the maximum element in s, update the sum and move the maximum element to t
sum_values[0] += v - max(s)
t[max(s)] += 1
s[max(s)] -= 1
if s[max(s)] == 0:
del s[max(s)]
s[v] += 1
def rem(v, s, t, sum_values):
# If the element is present in t, remove it from t
if t[v] > 0:
t[v] -= 1
if t[v] == 0:
del t[v]
return
# Subtract the element from the sum and remove it from s
sum_values[0] -= v
s[v] -= 1
if s[v] == 0:
del s[v]
# If t is not empty, add the smallest element from t to s and update the sum
if t:
min_t = min(t)
sum_values[0] += min_t
s[min_t] += 1
t[min_t] -= 1
if t[min_t] == 0:
del t[min_t]
def minimumCost(a, k, d):
n = len(a)
ans = float('inf')
sum_values = [0]
s, t = Counter(), Counter()
# Initialize the counters and sum for the initial subarray
for i in range(1, d + 2):
add(a[i], s, t, sum_values, k)
for i in range(1, n - k + 2):
ans = min(ans, sum_values[0] + a[0])
if i + d + 1 < n:
add(a[i + d + 1], s, t, sum_values, k)
rem(a[i], s, t, sum_values)
return ans
if __name__ == "__main__":
# Input array
arr = [1, 3, 2, 6, 4, 2]
# Number of elements that can be changed in a subarray
k = 3
# Distance between two consecutive subarrays
len_d = 3
# Calculate the minimum cost
minCost = minimumCost(arr, k, len_d)
# Print the minimum cost
print(f"Minimum cost: {minCost}")
# This code is contributed by Susobhan Akhuli