Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Algorithm
To solve this, we will follow these steps ?
- Create a copy of the array
numsand sort it - Calculate cost for ascending order: sum of absolute differences between original and sorted positions
- Calculate cost for descending order: sum of absolute differences between original and reverse sorted positions
- Return the minimum of both costs
Example
Let's implement this step by step ?
class Solution:
def solve(self, nums):
temp = nums.copy()
temp.sort()
c1 = 0 # cost for ascending order
c2 = 0 # cost for descending order
n = len(nums)
for i in range(n):
# Cost for ascending order
if nums[i] != temp[i]:
c1 += abs(nums[i] - temp[i])
# Cost for descending order
if nums[i] != temp[n-1-i]:
c2 += abs(nums[i] - temp[n-i-1])
return min(c1, c2)
# Test the solution
ob = Solution()
result = ob.solve([2, 5, 4])
print(f"Minimum cost: {result}")
Minimum cost: 2
How It Works
For the input [2, 5, 4]:
-
Sorted array:
[2, 4, 5] - Ascending cost: |2-2| + |5-4| + |4-5| = 0 + 1 + 1 = 2
- Descending cost: |2-5| + |5-4| + |4-2| = 3 + 1 + 2 = 6
- Minimum: min(2, 6) = 2
Step-by-Step Example
Let's trace through another example with [3, 1, 4, 2] ?
def find_min_cost_detailed(nums):
temp = nums.copy()
temp.sort()
print(f"Original: {nums}")
print(f"Sorted: {temp}")
c1 = c2 = 0
n = len(nums)
print("\nCalculating costs:")
for i in range(n):
# Ascending cost
asc_diff = abs(nums[i] - temp[i])
c1 += asc_diff
# Descending cost
desc_diff = abs(nums[i] - temp[n-1-i])
c2 += desc_diff
print(f"Position {i}: {nums[i]} vs {temp[i]} (asc) = {asc_diff}, vs {temp[n-1-i]} (desc) = {desc_diff}")
print(f"\nAscending cost: {c1}")
print(f"Descending cost: {c2}")
print(f"Minimum cost: {min(c1, c2)}")
return min(c1, c2)
find_min_cost_detailed([3, 1, 4, 2])
Original: [3, 1, 4, 2] Sorted: [1, 2, 3, 4] Calculating costs: Position 0: 3 vs 1 (asc) = 2, vs 4 (desc) = 1 Position 1: 1 vs 2 (asc) = 1, vs 3 (desc) = 2 Position 2: 4 vs 3 (asc) = 1, vs 2 (desc) = 2 Position 3: 2 vs 4 (asc) = 2, vs 1 (desc) = 1 Ascending cost: 6 Descending cost: 6 Minimum cost: 6
Conclusion
This algorithm computes the minimum cost to sort an array by comparing the cost of ascending versus descending arrangements. The time complexity is O(n log n) due to sorting, and space complexity is O(n) for the temporary array.
Advertisements
