- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 minimum total cost for equalizing list elements in Python
Suppose we have two lists of numbers called nums and costs. Now consider, there is an operation where we can increase or decrease nums[i] for cost costs[i]. We can perform any number of these operations, and we want to make all elements equal in the nums. We have to find the minimum total cost required.
So, if the input is like nums = [3, 2, 4] costs = [1, 10, 2], then the output will be 5, as if we can decrease the number 3 into 2 for a cost of 1. Then we can decrement 4 two times for a cost of 2 each.
To solve this, we will follow these steps −
Define a function helper() . This will take target
total := 0
for each i,n in enumerate(nums), do
if target is not same as n, then
total := total + |n-target| * costs[i]
return total
From the main method, do the following:
low := 0, high := maximum of nums
while low < high is non-zero, do
mid := (low + high) / 2
if helper(mid) < helper(mid+1), then
high := mid
otherwise,
low := mid + 1
return helper(low)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, costs): def helper(target): total = 0 for i,n in enumerate(nums): if target != n: total += abs(n-target) * costs[i] return total low,high = 0, max(nums) while low < high: mid = low + high >> 1 if helper(mid) < helper (mid+1): high = mid else: low = mid + 1 return helper(low) ob = Solution() nums = [3, 2, 4] costs = [1, 10, 2] print(ob.solve(nums, costs))
Input
[3, 2, 4], [1, 10, 2]
Output
5
- Related Articles
- Program to find minimum cost for painting houses in Python
- Program to find total cost for completing all shipments in python
- Program to find minimum cost to reduce a list into one integer in Python
- Program to find minimum cost to merge stones 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 Out the Minimum Cost to Purchase All in Python
- Program to find minimum deletion cost to avoid repeating letters in Python
- C Program for Minimum Cost Path
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Program to find minimum total distance between house and nearest mailbox in Python
- Python program to find sum of elements in list
- Program to find minimum cost to paint fences with k different colors in Python
- Program to find minimum amplitude after deleting K elements in Python
