Minimum of sum of absolute values

前端 未结 2 1060
闹比i
闹比i 2020-12-28 19:50

Problem statement:

There are 3 arrays A,B,C all filled with positive integers, and all the three arrays are of the same size.

Find min(|a-b|+|b-c|+|c-a|) whe

2条回答
  •  鱼传尺愫
    2020-12-28 20:19

    I would write a really simple program like this:

    #!/usr/bin/python
    import sys, os, random
    A = random.sample(range(100), 10)
    B = random.sample(range(100), 10)
    C = random.sample(range(100), 10)
    minsum = sys.maxint
    for a in A:
     for b in B:
      for c in C:
       print 'checking with a=%d b=%d c=%d' % (a, b, c)
       abcsum = abs(a - b) + abs(b - c) + abs(c - a)
       if abcsum < minsum:
        print 'found new low sum %d with a=%d b=%d c=%d' % (abcsum, a, b, c)
        minsum = abcsum
    

    And test it over and over until I saw some pattern emerge. The pattern I found here is what would be expected: the numbers that are closest together in each set, regardless of whether the numbers are "high" or "low", are those that produce the smallest minimum sum. So it becomes a nearest-number problem. For whatever that's worth, probably not much.

提交回复
热议问题