- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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

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

- Related Articles
- 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
- Program to find minimum operations to reduce X to zero in Python
- Minimum Cost to cut a board into squares 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 minimum cost for painting houses 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
- Program to find minimum cost to paint fences with k different colors in Python
- Python program to find Maximum and minimum element’s position in a list?
- 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