- Related Questions & Answers
- Program to find one minimum possible interval to insert into an interval list in Python
- Program to find minimum total cost for equalizing list elements in Python
- Minimum Cost to cut a board into squares in Python
- Program to Find Out the Minimum Cost to Purchase All in Python
- Minimum Cost to cut a board into squares in C++
- Program to find minimum cost to paint fences with k different colors in Python
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Program to find minimum cost to pick up gold in given two locations in Python
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Find minimum adjustment cost of an array in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Find the minimum cost to reach destination using a train
- Find minimum cost to buy all books in C++
- Program to find the minimum cost to arrange the numbers in ascending or descending order in Python
- Program to find island count by adding blocks into grid one by one in Python

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

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

[2, 3, 4, 5, 6]

45

Advertisements