Last active 1729748267

Revision 81aa9a57861cca1a2e775993ddf7f29943b61f79

leet.cs Raw
1int Foo(int[] arr1, int[] arr2) {
2 Array.Sort(arr2);
3 Dictionary<(int, int), int> dictionary = new Dictionary<(int, int), int>();
4
5 int Bar(int i, int prev) {
6 if (i == arr1.Length) return 0;
7 if (dictionary.ContainsKey((i, prev))) return dictionary[(i, prev)];
8
9 int cost = int.MaxValue;
10 if (arr1[i] > prev) {
11 cost = Bar(i + 1, arr1[i]);
12 }
13
14 int idx = Array.BinarySearch(arr2, prev + 1);
15 if (idx < 0) idx = ~idx;
16 if (idx < arr2.Length) {
17 try {
18 checked {
19 cost = Math.Min(cost, 1 + Bar(i + 1, arr2[idx]));
20 }
21 } catch (OverflowException) {
22 return -1;
23 }
24 }
25
26 dictionary[(i, prev)] = cost;
27 return cost;
28 }
29
30 int result = Bar(0, int.MinValue);
31 return result == int.MaxValue ? -1 : result;
32}
33
34int[] arr1 = {1,5,3,6,7};
35int[] arr2 = {1,6,3,3};
36int result = Foo(arr1, arr2);
37Console.WriteLine(result);