I want to optimize my code for following question:

A company sells dumbbells in pairs. These are weights for exercising. They receive a shipment of dumbbells weighing anywhere from 1 unit up to a certain maximum.

A pair can only be sold if their weights are sufficiently close: no greater than 1 unit difference.

Given an inventory of various weights, determine the maximum number of pairs the company can sell.

For example, if there are 2 dumbbells of weight 1, 4 of weight 2, 3 of weight 3 and 1 of weight 4, (arr = [2,4,3,1])

they can be paired as [1,1], [2,2], [2,2], [3,3], [3,4] for a total of 5 pairs.

i-th element is the number of dumbbells with a weight of i+1.

For example:

if arr  = [3,5,4,3]
number of pairs will be 7 as shown below: 
initial array is to be converted to  [3(1's),5(2's),4(3's),3(4's)] i.e [1,1,1,2,2,2,2,2,3,3,3,3,4,4,4]

Now we need to make pairs like this [1,1][1,2][2,2][2,2][3,3][3,3][4,4] remaining last 4 is left as it is single. So total number of pairs is 7. Following is my solution for the same:

def taskOfPairing(arr):
    n = len(arr)
    count = 0
    newList = []
    for i, j in enumerate(arr):
        newList += [i + 1]*j
    count1 = 0
    k = 1
    n1 = len(newList)
    while r<n1:
        if newList[r]-newList[l] < k:
            count1 += 1
            n1 = len(newList)
            if len(newList) == 1:
    return count1

arr= [3,5,4,3]

output = 7

My output works but only when there is small numbers in list like arr = [3,5,4,3] or [2,4,3,1].

If I try putting large numbers in list for example, arr = [100000,200000,300000,400000] my code will not work and will cause a lot of delay in execution. Can anyone let me know what I am doing wrong in this code. My apologies to stack overflow for asking naive questions.


1 Answer 1


The task doesn't require to generate a list of pairs - just to count them. So:

  • take as much 1-1 pairs as you can ('count += arr[0]//2');
  • if one dumbbell is left ('arr[0]' is odd) and there are dumbbells of weight 2, increase count and reduce 'arr1' by one;
  • repeat the process for weights 2, 3 and so on.

Also, the sorting is excessive - just FYI.

Oh, and be sure to read PEP8 and apply it to your code.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.