- Related Questions & Answers
- 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
- C Program for Minimum Cost Path
- Program to Find Out the Minimum Cost to Purchase All in Python
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Minimum Cost For Tickets in C++
- Program to find minimum cost to paint fences with k different colors in Python
- Find minimum adjustment cost of an array in Python
- Program to find minimum cost to pick up gold in given two locations in Python
- Python Program for Min Cost Path
- Python program to find sum of elements in list
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Program to find total unique duration from a list of intervals in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Find minimum cost to buy all books in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

[3, 2, 4], [1, 10, 2]

5

Advertisements