Challenge : to find the minimum and maximum sums which can be obtained out of four elements from the list containing 5 elements.
Approach followed : Sort the list in descending and ascending order and store them into two different variables. Finding the sum of first 4 elements in both of the lists. One sum would be the minimum most and the second one would be the maximum most.
Code :
arr = [2,1,3,4,5]
arr.sort()
asc = arr
print(asc[0],asc[1],asc[2],asc[3])
arr.sort(reverse = True)
des = arr
print(des[0],des[1],des[2],des[3])
maxi = 0
mini = 0
for j in range(4) :
mini = mini + asc[j]
print(mini, asc[j])
maxi = maxi + des[j]
print(maxi,des[j])
print(mini, maxi)
Few print statements are introduced here for debugging purpose. As visible in the code, bot the sorted versions are printed before entering into the for loop and after entering into the loop. Its clearly visible as seen in the output that, the list which should be holding the elements in ascending order is having the elements in the descending order.
Output :
11 12 13 14 - list in the ascending order
15 14 13 12 - list in the descending order
15 15 - round 0
15 15
29 14 - round 1
29 14
42 13 - round 2
42 13
54 12 - round 3
54 12
54 54 - final output
why the elements present in one particular list change their order when they enter into the for loop ??