def findMinimumCost(arr):
# Step 1: Sort the array to find the median arr_sorted = sorted(arr)
n = len(arr)
median = arr_sorted[n // 2] # Median for minimizing cost # Step 2: Calculate total cost to make all elements equal to the median total_cost = 0 for i in range(n):
total_cost += abs(arr[i] - median)
return total_cost
OR
def findMinimumCost(arr):
n = len(arr)
total_cost = 0 # Start by targeting the last element current_value = arr[-1]
# Traverse from the second last element to the first for i in range(n - 2, -1, -1):
if arr[i] != current_value:
# Find the difference that needs to be applied to this prefix difference = current_value - arr[i]
# Add the cost of this operation (which is |difference|) total_cost += abs(difference)
# Update the current value for all future prefixes to match this new level current_value = arr[i]
return total_cost
OR
def findMinimumCost(arr):
total_cost = 0 # Calculate the sum of absolute differences between adjacent elements for i in range(1, len(arr)):
total_cost += abs(arr[i] - arr[i - 1])
return total_cost