Getting the lowest possible sum from numbers' difference

后端 未结 10 1282
滥情空心
滥情空心 2020-12-23 22:19

I have to find the lowest possible sum from numbers\' difference.

Let\'s say I have 4 numbers. 1515, 1520, 1500 and 1535. The lowest sum of difference is 30, becaus

10条回答
  •  生来不讨喜
    2020-12-23 22:52

    Something like

    1. Sort List
    2. Find Duplicates
    3. Make the duplicates a pair
    4. remove duplicates from list
    5. break rest of list into pairs
    6. calculate differences of each pair
    7. take lowest amounts

    In your example you have 8 number and need the best 3 pairs. First sort the list which gives you

    1561, 1572, 1572, 1609, 1682, 1731, 1731, 2041
    

    If you have duplicates make them a pair and remove them from the list so you have

    [1572, 1572] = 0
    [1731, 1731] = 0
    L = { 1561, 1609, 1682, 2041 }
    

    Break the remaining list into pairs, giving you the 4 following pairs

    [1572, 1572] = 0
    [1731, 1731] = 0
    [1561, 1609] = 48
    [1682, 2041] = 359
    

    Then drop the amount of numbers you need to.

    This gives you the following 3 pairs with the lowest pairs

    [1572, 1572] = 0
    [1731, 1731] = 0
    [1561, 1609] = 48
    

    So

    0 + 0 + 48 = 48
    

提交回复
热议问题