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


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   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;
         int temp =;
         temp +=;
      return ans;
   vector<int> v = {2,4,3};
   Solution ob;
   cout <<ob.connectSticks(v);




Published on 17-Mar-2020 10:36:05