简体   繁体   中英

Where is the flaw in my algorithm to find whether there exists a permutation of two arrays A,B such that they have (A[i]+B[i]) >= k

For example, with

k=10
A=[2,1,3]
B=[7,8,9]

the answer is yes because you can re-arrage the elements to be

A=[1,2,3]
B=[9,8,7]

which then it's true that A[i]+B[i] >= 10 = k for i=0,1,2 . My algorithm is greedy, like

int k = parameters[1];
int[] A = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int?[] B = Array.ConvertAll(Console.ReadLine().Split(' '), Extensions.ToNullableInt);

Array.Sort(B);
for(int j = 0; j < A.Length; ++j)
{
    bool found = false;
    for(int m = 0; j < B.Length && !found; ++j)
    {
        if(B[m] == null)
            continue;
        if((A[j] + B[m]) >= k)
        {
            found = true;
            B[m] = null;
        }
    }
    if(!found)
    {
        Console.WriteLine("NO");
        return;
    }
}
Console.WriteLine("YES");

and I can't think of any cases it would fail.

Sort A , sort B in descending order (prove that it's the best possibility you can achieve) and check:

  int[] A = new int[] { 2, 1, 3 };
  int[] B = new int[] { 7, 8, 9 };

  int maxK = A
    .OrderBy(x => x)
    .Zip(B.OrderByDescending(x => x), (a, b) => a + b)
    .Min();

And you'll get maxK == 10 thus you can find a permutation for all k <= maxK == 10 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM