Skip to content

Instantly share code, notes, and snippets.

@kavilivishnu
Last active August 9, 2020 20:02
Show Gist options
  • Save kavilivishnu/10268f384f064df89b4fe607e0921b57 to your computer and use it in GitHub Desktop.
Save kavilivishnu/10268f384f064df89b4fe607e0921b57 to your computer and use it in GitHub Desktop.
Minimize the sum of elements in an array
'''
The code below is to minimize the sum of all elements in an array. I have provided the time that the code is taking to execute too.
Miniize the sum was the question that was asked in a coding contest that I have recently participated in, and got to know that
it if a frequently asked question.
'''
import time
# The start time is not that useful in this program. But mentioned just incase
t1 = time.process_time()
a = [20, 7, 5, 4]
for i in range(len(a)-1):
b = max(a)
c = b // 2
a.append(c)
a.remove(b)
# The below line were written out of for loop only for the purpose to see the sum for every iteration. It can be put inside the
# loop according the user's wish.
final = a
res = reduce(lambda a, b: a + b, final)
print("Min sum " + "-", res)
# End time is important because you should be knowing how long your code is taking to execute
t2 = time.process_time()
# Print start time i.e. even before the actual code starts to executes
print(t1)
# Will print end time
print(t2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment