

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find the minimum cost to arrange the numbers in ascending or descending order in Python
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 −
Example
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]))
Input
[2, 5, 4]
Output
2
- 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 minimum cost to merge stones in Python
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Program to find minimum cost for painting houses in Python
- Program to find minimum cost to connect all points in Python
- Program to find minimum cost to cut a stick in Python
- Program to find minimum cost to hire k workers 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?
- Program to find minimum deletion cost to avoid repeating letters in Python
- Python program to sort the elements of an array in descending order
- Python program to sort out words of the sentence in ascending order
- Python program to sort the elements of an array in ascending order
- Program to find overlapping intervals and return them in ascending order in Python
Advertisements