- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- 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
- Program to find minimum cost to cut a stick in Python
- Program to find minimum cost to merge stones in Python
- Minimum Cost to cut a board into squares in Python
- Program to find minimum cost for painting houses in Python
- Program to find minimum operations to reduce X to zero in Python
- Program to find minimum cost to connect all points 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
- 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

Advertisements