- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- How to I connect to wifi network on Android programmatically?
- Prim’s (Minimum Spanning Tree) MST Algorithm
- Kruskal’s (Minimum Spanning Tree) MST Algorithm
- Array element with minimum sum of absolute differences?
- Add minimum number to an array so that the sum becomes even in C++?
- How to find the minimum values of two or more fields in MySQL?
- Is there a way to retrieve the minimum value of fields in MySQL?
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?
- C++ Program to Find the Minimum value of Binary Search Tree
- Find minimum value with MongoDB?
- Get maximum and minimum value in MongoDB?
- How to change the minimum value of a JSlider in Java?
- How to find the minimum value of an array in JavaScript?
- How to set minimum size limit for a JFrame in Java

- 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 some sticks with positive integer lengths. We can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. This will be performed until there is one stick remaining. We have to find the minimum cost of connecting all the given sticks into one stick in this way. So if the stack is [2,4,3], then the output will be 14.

To solve this, we will follow these steps −

- Define a max heap priority queue pq
- insert all elements of s into pq
- ans := 0
- while pq has more than one element
- temp := top of the queue, delete top from pq
- temp := temp + top element of pq, and delete from pq
- ans := ans + temp
- insert temp into pq

- return ans

Let us see the following implementation to get better understanding −

class Solution { public: int connectSticks(vector<int>& s) { priority_queue <int, vector<int>, greater<int> > pq; for(int i =0;i<s.size();i++)pq.push(s[i]); int ans = 0; while(pq.size()>1){ int temp = pq.top(); pq.pop(); temp += pq.top(); pq.pop(); ans+=temp; pq.push(temp); } return ans; } };

[2,4,3]

14

Advertisements