Minimum Cost to Connect Sticks in C++

C++Server Side ProgrammingProgramming

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

Example

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;
   }
};

Input

[2,4,3]

Output

14
raja
Published on 17-Mar-2020 10:36:05
Advertisements