You are given an array of integers representing the weights of chocolates. Your goal is to minimize the cost of transforming this array into either an ascending or a descending order. The cost of transforming an element in the array is defined as the absolute difference between the original value and the new value.
Transformation Rules:
You can either increase or decrease any element in the array.
The cost incurred by changing a number
𝑥 to 𝑦 is given by ∣𝑥−𝑦|
Requirements
The transformed array should be in ascending or in descending order.
Your task is to find the minimum possible total cost for the transformation.
Input
The first line contains an integer
𝑛
n (the size of the array).
The following
𝑛
n lines contain integers representing the elements of the array.
Output
Return an integer representing the minimum total cost of transforming the array into ascending or descending order.
Any ideas on the solution of it, I gave a greedy solution, but I think that was wrong only.
Edit: Added examples -
Input - [0,1,2,5,6,5,7]; Output - 1
Input - [9,8,7,2,3,3]; Output - 1