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

 Live Demo

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

Updated on: 07-Oct-2020

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements