Suppose we have a list of numbers called nums, we have to find the minimum cost to sort the list in any order (Ascending or Descending). Here the cost is the sum of differences between any element's old and new value.
So, if the input is like [2, 5, 4], then the output will be 2.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): temp=nums.copy() temp.sort() c1=0 c2=0 n=len(nums) for i in range(n): if nums[i]!=temp[i]: c1+=abs(nums[i]-temp[i]) if nums[i]!=temp[n-1-i]: c2+=abs(nums[i]-temp[n-i-1]) return min(c1,c2) ob = Solution() print(ob.solve([2, 5, 4]))
[2, 5, 4]