int Foo(int[] arr1, int[] arr2) { Array.Sort(arr2); Dictionary<(int, int), int> dictionary = new Dictionary<(int, int), int>(); int Bar(int i, int prev) { if (i == arr1.Length) return 0; if (dictionary.ContainsKey((i, prev))) return dictionary[(i, prev)]; int cost = int.MaxValue; if (arr1[i] > prev) { cost = Bar(i + 1, arr1[i]); } int idx = Array.BinarySearch(arr2, prev + 1); if (idx < 0) idx = ~idx; if (idx < arr2.Length) { cost = Math.Min(cost, 1 + Bar(i + 1, arr2[idx])); } dictionary[(i, prev)] = cost; return cost; } int result = Bar(0, int.MinValue); return result == int.MaxValue ? -1 : result; } int[] arr1 = {1, 5, 3, 6, 7}; int[] arr2 = {1, 3, 2, 4}; int result = Foo(arr1, arr2); Console.WriteLine(result);