Program to find the minimum cost to arrange the numbers in ascending or descending order in Python

PythonServer Side ProgrammingProgramming

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]|
  • 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
raja
Published on 06-Oct-2020 06:32:18
Advertisements