[InterviewBit] Connect Ropes

Connect Ropes

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
int Solution::solve(vector<int> &A) {
int res = 0;
priority_queue<int, vector<int>, greater<int>> q;
for(auto a : A) q.push(a);
while(q.size() > 1) {
auto a = q.top(); q.pop();
auto b = q.top(); q.pop();
res += a + b;
q.push(a + b);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/15/PS/interviewbit/connect-ropes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.