Program to find minimum cost to reduce a list into one integer in Python


Suppose we have a list of numbers called nums. We can reduce the length of nums by taking any two numbers, removing them, and appending their sum at the end. The cost of doing this operation is the sum of the two integers we removed. We have to find the minimum total cost of reducing nums to one integer.

So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be 45, as we take 2 and 3 then remove to get [4, 5, 6, 5], then we take 4 and 5 then remove to get [6, 5, 9], then take 6 and 5, then remove them and we get [9, 11], and finally remove 9 and 11, we will get 19. So the sum is 45.

To solve this, we will follow these steps −

  • make a heap by using elements present in nums
  • ans := 0
  • while size of nums >= 2, do
    • a := top most element of heap nums
    • b := top most element of heap nums
    • ans := ans + a + b
    • insert a+b into heap nums
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      import heapq
      heapq.heapify(nums)
      ans = 0
      while len(nums) >= 2:
         a = heapq.heappop(nums)
         b = heapq.heappop(nums)
         ans += a + b
         heapq.heappush(nums, a + b)
      return ans
ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums))

Input

[2, 3, 4, 5, 6]

Output

45

Updated on: 19-Oct-2020

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements