int Foo(int[] arr1, int[] arr2) { Array.Sort(arr2); Dictionary<(int, int), int> memo = new Dictionary<(int, int), int>(); int DP(int i, int prev) { if (i == arr1.Length) return 0; if (memo.ContainsKey((i, prev))) return memo[(i, prev)]; int cost = int.MaxValue; if (arr1[i] > prev) { int nextCost = DP(i + 1, arr1[i]); if (nextCost != int.MaxValue) { cost = Math.Min(cost, nextCost); } } int idx = Array.BinarySearch(arr2, prev + 1); if (idx < 0) idx = ~idx; if (idx < arr2.Length) { int nextCost = DP(i + 1, arr2[idx]); if (nextCost != int.MaxValue) { cost = Math.Min(cost, 1 + nextCost); } } memo[(i, prev)] = cost; return cost; } int result = DP(0, int.MinValue); return result == int.MaxValue ? -1 : result; } int[] arr1 = { 0, 11, 6, 1, 4, 3 }; int[] arr2 = { 5, 4, 11, 10, 1, 0 }; int minOperations = Foo(arr1, arr2); Console.WriteLine(minOperations); // output: 5