Minimum/maximum distance
296. Best Meeting Point
1 min readJul 18, 2020
The solution is from [1]. [1] also introduces several solutions for the variations of this problem.
class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
vector<int> x, y;
const int R = grid.size(), C = grid[0].size();
for(int i = 0; i<R;++i )
for(int j=0;j<C;++j)
{
if(grid[i][j]==1)
{
x.push_back(j);
y.push_back(i);
}
}
sort(x.begin(), x.end());
sort(y.begin(), y.end());
int mx = x[x.size()/2], my = y[y.size()/2];
int ret = 0;
for(int i = 0;i<x.size();++i)
{
ret += (abs(mx-x[i])+abs(my-y[i]));
}
return ret;
}
};
1515. Best Position for a Service Centre
See my previous post HERE.