Help in codeforces Office Keys

problem link:

solution :

#include<bits/stdc++.h>
using namespace std;

const int maxm = 2 * 1e3 + 5;
int a[maxm], b[maxm];
int n, k, p;
int dp[maxm][maxm];

int checker(int pos, int key)
{
  if (pos >= n) return 0;
  if (key >= k) return 1e9;
  if (dp[pos][key] != -1) return dp[pos][key];
  int ans = INT_MAX;
  
  for (int i = key; i < k; i++) {
    int temp = abs(a[pos] - b[i]) + abs(b[i] - p);
    int temp2 = checker(pos + 1, i + 1);
    int temp3 = max(temp, temp2);
    ans = min(ans, temp3);
  }
  return dp[pos][key] = ans;
}

void solve()
{

  cin >> n >> k >> p;
  memset(dp, -1, sizeof dp);
  for (int i = 0; i < n; i++) cin >> a[i];
  sort(a, a + n);
  for (int i = 0; i < k; i++) cin >> b[i];
  sort(b, b + k);
  cout << checker(0, 0) << endl;
}

int32_t main()
{

  ios_base:: sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  solve();
  return 0;
}

this solution is giving tle

and

this is working
isn’t it the both code having same time complexity

please help @akshitm16 @ssjgz