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

For example, when

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

the answer is yes because you can reassign items

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

and then it is true that A[i]+B[i] >= 10 = kfor i=0,1,2. My algorithm is greedy for example

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 cannot think of any cases that he will fail.

+4
source share
1 answer

Sort A, sort Bin descending order (prove that this is the best opportunity 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();

maxK == 10, , k <= maxK == 10;

+2

Source: https://habr.com/ru/post/1651294/


All Articles