Walmart Logo

Asked in Walmart

Minimum Cost to Connect Sticks

You are provided with an array, ARR, of N positive integers. Each integer represents the length of a stick. The task is to connect all sticks into one by paying a cost to join two sticks at a time. If you join two sticks with lengths X and Y, the cost is X + Y, and the resulting stick has a length of (X + Y). Determine the minimum cost to connect all the sticks into a single stick.

Input:

- The first line contains an integer T, representing the number of test cases.
- For each test case:
   * The first line contains an integer N, denoting the number of sticks.
   * The second line contains N space-separated integers, representing the length of each stick.

Output:

For each test case, output the minimum cost to connect all the sticks into one. Each result should be printed on a new line.

Example:

Input:
T = 1
N = 4
ARR = [2, 4, 3, 6]
Output:
29
Explanation:

We first join sticks of lengths 2 and 3, the cost is 5. Resulting sticks are [5, 4, 6].
Next, join sticks of lengths 5 and 4, the cost is 9. Resulting sticks are [9, 6].
Finally, join sticks of lengths 9 and 6, the cost is 15. The total cost is 5 + 9 + 15 = 29.

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 104
  • 1 ≤ Val ≤ 5*103

Where:
- T is the number of test cases.
- N is the number of sticks.
- Val is the length of each stick.

Time Limit: 1 sec

AnswerBot
4mo

Find the minimum cost to connect all sticks into one by joining two sticks at a time.

  • Sort the array of stick lengths in non-decreasing order.

  • Keep adding the two smallest sticks at a time to minimize c...read more

Help your peers!
Select
Add answer anonymously...

Top SDE-2 Interview Questions Asked at Walmart

Q. Maximum Length Pair Chain Problem Statement You are provided with 'N' pairs of i...read more
Q. Bipartite Graph Problem Statement Determine if a given graph is bipartite. A gra...read more
Q. Can you explain the DHCP Protocol?
SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits