
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- How to arrange the fractions in ascending order and descending order?
- Arrange the following numbers in ascending order:$9801,\ 25751,\ 36501,\ 38802$
- Program to arrange cards so that they can be revealed in ascending order in Python
- Arrange the following in ascending order.\( -9,4,5,-4,0 \)
- Program to Find Out the Minimum Cost to Purchase All in Python
- Program to find minimum cost to merge stones in Python
- Arrange the numbers in descending order :$\frac{4}{5}, \frac{2}{7}, \frac{5}{3}$
- Arrange the following numbers in the ascending order :$\sqrt{3},\ \sqrt[3]{4},\ \sqrt[4]{10}$
- 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 cost for painting houses in Python
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Python program to sort the elements of an array in descending order
- Program to find overlapping intervals and return them in ascending order in Python

Advertisements