In this article, we will discuss about the TCS Coding Question which is asked in the TCS placement test. This type of Coding Questions will help you to crack your upcoming TCS exam as well as during your inteview process.
TCS Coding Question Day 1 Slot 2 – Question 2
Given N gold wires, each wire has a length associated with it. At a time, only two adjacent small wires are assembled at the end of a large wire and the cost of forming is the sum of their length. Find the minimum cost when all wires are assembled to form a single wire.
For Example:
Suppose, Arr[]={7,6,8,6,1,1,}
{7,6,8,6,1,1}-{7,6,8,6,2} , cost =2
{7,6,8,6,2}- {7,6,8,8}, cost = 8
{7,6,8,8} – {13,8,8}, cost=13
{13,8,8} -{13,16}, cost=16
{13, 16} – {29}, cost =29
2+8+13+16+29=68
Hence , the minimum cost to assemble all gold wires is 68.
Constraints
1<=N<=30
1<= Arr[i]<=100
Example 1:
Input
6 -> Value of N, represent size of Arr
7 -> Value of Arr[0], represent length of 1st wire
6 -> Value of Arr[1], represent length of 2nd wire
8 -> Value of Arr[2] , represent length of 3rd wire
6 -> Value of Arr[3], represent length of 4th wire
1 -> Value of Arr[4], represent length of 5th wire
1 -> Value of Arr[5], represent length of 6th wire
Output :
68
Example 2:
Input
4 -> Value of N, represents size of Arr
12 -> Value of Arr[0], represents length of 1st wire
2 -> Value of Arr[1], represent length of 2nd wire
2 -> Value of Arr[2], represent length of 3rd wire
5 -> Value of Arr[3], represent length of 4th wire
def mini(l1,n):
count=n-1
n1=0
lis=l1
while True:
N=[lis[i]+lis[i+1] for i in range(len(lis)) if i+1<len(lis)]
c=sum(N)
j=0
for i in range(len(N)):
if N[i]<c:
c=N[i]
j=N.index(N[i])
n1+=N[j]
lis=lis[0:j]+[N[j]]+lis[j+2:n]
print(lis)
count-=1
if count==0:
break
return n1
n=int(input())
l1=list(map(int,input().split()))
print(mini(l1,n))
Code written in python
def mini(l1,n):
count=n-1
n1=0
lis=l1
while True:
N=[lis[i]+lis[i+1] for i in range(len(lis)) if i+1<len(lis)]
c=sum(N)
j=0
for i in range(len(N)):
if N[i]<c:
c=N[i]
j=N.index(N[i])
n1+=N[j]
lis=lis[0:j]+[N[j]]+lis[j+2:n]
print(lis)
count-=1
if count==0:
break
return n1
n=int(input())
l1=list(map(int,input().split()))
print(mini(l1,n))