#include <bits/stdc++.h>
using namespace std;
using ll = long long;
bool cmp(pair<ll, ll> a, pair<ll, ll> b) { return a.second > b.second; }
bool cmp2(vector<ll> a, vector<ll> b) { return a.size() > b.size(); }
int main() {
  ll n, m;
  cin >> n >> m;
  vector<pair<ll, ll>> vp(n);
  for (ll i = 0; i < n; i++) {
    ll s, r;
    cin >> s >> r;
    s--;
    vp[i] = make_pair(s, r);
  }
  sort(vp.begin(), vp.end(), cmp);
  vector<vector<ll>> g(m, vector<ll>(1));
  ll mxsz = 0;
  for (ll i = 0; i < n; i++) {
    g[vp[i].first].push_back(vp[i].second + g[vp[i].first].back());
    mxsz = max(mxsz, (ll)g[vp[i].first].size());
  }
  sort(g.begin(), g.end(), cmp2);
  ll ans = 0;
  for (ll i = 0; i < mxsz; i++) {
    ll now = 0;
    vector<ll> hoge;
    for (ll j = 0; j < m; j++) {
      if (i < g[j].size()) {
        if (g[j][i] > 0) now += g[j][i];
      }
      if (g[j].size() < i) break;
    }
    ans = max(ans, now);
  }
  cout << max(0LL, ans) << endl;
}
