- Related Questions & Answers
- Program to Find Out the Minimum Cost to Purchase All in Python
- Program to arrange cards so that they can be revealed in ascending order in Python
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Program to find minimum swaps to arrange a binary grid using Python
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Python program to sort out words of the sentence in ascending order
- Python program to sort the elements of an array in ascending order
- Python program to sort the elements of an array in descending order
- Program to find minimum total cost for equalizing list elements in Python
- Program to find overlapping intervals and return them in ascending order in Python
- C# Program to order array elements in descending order
- Program to find minimum cost to reduce a list into one integer in Python
- Program to find minimum cost to paint fences with k different colors in Python
- Find the minimum cost to reach destination using a train
- Program to find minimum cost to pick up gold in given two locations in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

- temp:= copy the array nums
- sort the list temp
- c1:= 0, c2:= 0
- n:= size of nums
- for i in range 0 to n, do
- if nums[i] is not same as temp[i], then
- c1 := c1 + |nums[i]-temp[i]|

- if nums[i] is not same as temp[n-1-i], then
- c2 := c2 + |nums[i]-temp[n-i-1]|

- if nums[i] is not same as temp[i], then
- return minimum of c1 and c2

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]

2

Advertisements