I was trying the bottom up solution. That was not working. Not sure where I went wrong-
include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mod=1e6+3;
int main() {
ll n, m;
cin>>n>>m;
ll* boys = new ll[n];
ll* girls = new ll[m];
for(int i = 0 ; i < n ; i++) {
cin>>boys[i];
}
for(int i = 0 ; i < m ; i++) {
cin>>girls[i];
}
sort(boys,boys + n);
sort(girls, girls + m);
ll dp[n][m];
for(int j = 0 ; j < m ; j++) {
dp[0][j] = abs(boys[0] - girls[j]);
}
for(int i = 0 ; i < n ; i++) {
dp[i][0] = abs(boys[i] - girls[0]);
}
for(int i = 1 ; i < n ; i++) {
for(int j = 1; j< m ; j++) {
dp[i][j] = min(dp[i-1][j-1]+abs(boys[i] - girls[j]),dp[i-1][j]);
}
}
cout<< dp[n-1][m-1] << endl;
return 0;
}