5

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.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
user6048670
  • 2,861
  • 4
  • 16
  • 20
  • 1
    Did you debug it?.. – Gilad Green Aug 15 '16 at 15:00
  • How exactly does `Extensions.ToNullableInt` work? – juharr Aug 15 '16 at 15:04
  • @Chris You only need to sort one of them. – juharr Aug 15 '16 at 15:04
  • 3
    m is always 0. I'm not sure Stack Overflow is the best place to have people test your code for you. – Buh Buh Aug 15 '16 at 15:05
  • @BuhBuh Good call on the type-o, but my code is failing even after I fix it – user6048670 Aug 15 '16 at 15:06
  • It's strange that as soon as a question falls into the category of _"demonstrate your cleverness"_, SO rules go out the window. In this case, your code actually **works** and you seem to be interested only in _" I can't think of any cases it would fail."_ which to me reads as _"[there is no actual problem to be solved](http://stackoverflow.com/help/dont-ask)"_ –  Sep 06 '16 at 04:07

1 Answers1

2

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;

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215