#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
//#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;
ll nD(vector<ll> &a)
{
  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  return mp.size();
}
void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (mp.count(0) == 1 && mp.size() > 1 && k == 1)
  {
    cout << -1;
    return;
  }
  cout << (mp.size() + k - 1) / k;
  return;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
//#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;
ll nD(vector<ll> &a)
{
  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  return mp.size();
}
void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (mp.count(0) == 1 && mp.size() > 1 && k == 1)
  {
    cout << -1;
    return;
  }
  // deb(mp.size());
  if (mp.size() <= k)
  {
    cout << 1;
    return;
  }
  ll m = 1 + (mp.size() - 1) / k;
  cout << m;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;

void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (k >= mp.size())
  {
    cout << 1;
    return;
  }
  if (k == 1)
  {
    if (mp.size() == 1)
      cout << 1;
    else
    {
      cout << -1;
    }
    return;
  }

  i = (mp.size() + k - 3) / (k - 1);
  // deb2(mp.size(), i);

  cout << i;
  return;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;

void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (k >= mp.size())
  {
    cout << 1;
    return;
  }
  if (k == 1)
  {
    if (mp.size() == 1)
      cout << 1;
    else
    {
      cout << -1;
    }
    return;
  }

  i = (mp.size() + k - 1) / k;
  // deb2(mp.size(), i);

  cout << i;
  return;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
//#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;

void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (k >= mp.size())
  {
    cout << 1;
    return;
  }
  if (mp.count(0) == 1 && mp.size() > 1 && k == 1)
  {
    cout << -1;
    return;
  }
  cout << (mp.size() + k - 1) / k;
  return;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#define TEST_CASES
//#define ONLINE_JUDGE

#define test   \
  long long t; \
  cin >> t;    \
  while (t--)
#ifndef ONLINE_JUDGE
#define reach(x) cout << "\n\t\t" << x << "\n\n";
#define deb(x) cout << #x << " " << x << '\n';
#define deb2(x, y) cout << #x << " --> " << x << " || " << #y << " --> " << y << '\n';
#define deb4(a, b, c, d) cout << #a << " = " << a << ", " << #b << " = " << b << ", " << #c << " = " << c << ", " << #d << " = " << d << '\n';
#else
#define reach(x)         //
#define deb(x)           //cout << #x << " " << x << '\n';
#define deb2(x, y)       //cout << #x << " --> " << x << " || " << #y << " --> " << y <<'\n';
#define deb4(a, b, c, d) // cout<<#a<<" = "<<a<<", "<<#b<<" = "<<b<<", "<<#c<<" = "<<c<<", "<<#d<<" = "<<d<<'\n';
#endif
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; i < n; i++)
#define boost()                     \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0);                      \
  cout << fixed << setprecision(11);
#define MEM(a, val) memset(a, val, sizeof(a));
#define inputarr(a, n)        \
  for (int i = 0; i < n; ++i) \
  cin >> a[i]

const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;

typedef long long ll;
typedef long double ld;
using namespace std;

void solve()
{
  ll n, i, j, k;
  cin >> n >> k;
  vector<ll> a(n);
  inputarr(a, n);
  //logic start

  unordered_set<ll> mp;
  mp.clear();
  for (ll x : a)
    mp.insert(x);
  if (k >= mp.size())
  {
    cout << 1;
    return;
  }
  if (mp.count(0) == 1 && mp.size() > 1 && k == 1)
  {
    cout << -1;
    return;
  }
--k;
  cout << (mp.size() + k - 1) / k;
  return;
}

signed main()
{
#ifdef ONLINE_JUDGE
  boost()
#endif
#ifdef TEST_CASES
      test
#endif
  {
    solve();
#ifdef TEST_CASES
    cout << '\n';
#endif
  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    ordered_set st;
    for(ll i = 0; i < n; i++){
        cin >> v[i];
        st.insert(v[i]);
    }
    if(k == 1 && st.size() > 1) {
        cout << "-1\n";
        return;
    }

    if(k >= st.size()) {
        cout << "1\n";
        return;
    }
    ll cur = st.size();
    ll ans = 1;
    cur -= k;
    ll x = k + 1;
    while(cur > 0){
        ll q = *(st.find_by_order(x - 1));
        set<ll> diff;
        ll o = x;
        while(o < x + k){
            ll p = *(st.find_by_order(o));
            diff.insert(p - q);
            o++;
        }
        cur = diff.size();
        cur -= k;
        ans++;

    }
    cout << ans << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


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

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    ll dist = 1;
    for (ll i = 0; i < n; i++){
        cin >> v[i];
        if (i) dist += (v[i] != v[i - 1]);
    }

    if(k == 1 && dist > 1) {
        cout << "-1\n"; return;
    }
    if(k >= dist){
        cout << "1\n"; return;
    }
    dist -= k;
    cout << 1 + (dist + k - 2) / (k - 1) << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


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

void solve(){
    ll n, k;
    cin >> n >> k;
    vector<ll> v(n);
    ll dist = 0;
    for(ll i = 0; i < n; i++) {
        cin >> v[i];
        if(i) dist += (v[i] != v[i - 1]);
    }
    if (k == 1 && dist > 1) {
       cout << -1 << '\n';
       return;
    }
    if(k >= dist) {
        cout << 1 << "\n";
        return;
    }
    dist -= k;
    cout << 1 + (dist + k - 2) / k - 1 << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


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

void solve(){
    ll n, k;
    cin >> n >> k;
    vector<ll> v(n);
    ll dist = 1;
    for(ll i = 0; i < n; i++) {
        cin >> v[i];
        if(i) dist += (v[i] != v[i - 1]);
    }
    if (k == 1 && dist > 1) {
       cout << -1 << '\n';
       return;
    }
    if(k >= dist) {
        cout << 1 << "\n";
        return;
    }
    dist -= k;
    cout << 1 + (dist + k - 2) / k - 1 << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


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

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    set<ll> st;
    for(ll i = 0; i < n; i++){
        cin >> v[i];
        st.insert(v[i]);
    }
    if(k == 1 && st.size() > 1) {
        cout << "-1\n";
        return;
    }

    if(k >= st.size()) {
        cout << "1\n";
        return;
    }
    ll cur = st.size(), ans = 0;
    while(cur > 0){
        ans++;
        cur -= k;
    }
    cout << ans << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    ordered_set st;
    for(ll i = 0; i < n; i++){
        cin >> v[i];
        st.insert(v[i]);
    }
    if(k == 1 && st.size() > 1) {
        cout << "-1\n";
        return;
    }

    if(k >= st.size()) {
        cout << "1\n";
        return;
    }
    ll cur = st.size();
    ll ans = 1;
    cur -= k;
    ll x = k + 1;
    while(cur > 0){
        ll q = *(st.find_by_order(x - 1));
        set<ll> diff;
        ll o = x;
        while(o < x + k - 1 && o < st.size()){
            ll p = *(st.find_by_order(o));
            diff.insert(p - q);
            o++;
        }
        cur = diff.size();
        cur -= k - 1;
        ans++;

    }
    cout << ans << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    ordered_set st;
    for(ll i = 0; i < n; i++){
        cin >> v[i];
        st.insert(v[i]);
    }
    if(k == 1 && st.size() > 1) {
        cout << "-1\n";
        return;
    }

    if(k >= st.size()) {
        cout << "1\n";
        return;
    }
    ll cur = st.size();
    ll ans = 1;
    cur -= k;
    ll x = k + 1;
    while(cur > 0){
        ll q = *(st.find_by_order(x - 1));
        set<ll> diff;
        ll o = x;
        while(o < x + k - 1){
            ll p = *(st.find_by_order(o));
            diff.insert(p - q);
            o++;
        }
        cur = diff.size();
        cur -= k - 1;
        ans++;

    }
    cout << ans << '\n';

}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


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

void solve(){
    ll n, k; cin >> n >> k;
    vector<ll> v(n);
    set<ll> st;
    for(ll i = 0; i < n; i++){
        cin >> v[i];
        st.insert(v[i]);
    }
    if(k == 1 && st.size() > 1) {
        cout << "-1\n";
        return;
    }
    ll cur = st.size();
    cout << (cur + k - 1) / k << '\n';
}

int main(){
    ios::sync_with_stdio(false); cin.tie(0);

    ll t; cin >> t; while(t--)

    solve();
}


#include <bits/stdc++.h>  // modifying on 18th Nov,2019 10:34am
using namespace std;

#define max_size 1000005
#define pb push_back
#define mp make_pair
#define ft first

#define sd second
#define ll long long
#define inf 1000000007
#define ll_max 1e18

#define bitcount(a) __builtin_popcountll(a)   // count set bits
#define lzcount(x) __builtin_clz(x)        // count leading zeros in binary representation of number
#define tzcount(x) __builtin_ctz(x)        // count trailing zeros in binary representation of number
#define digit(n) floor(log10(n)+1)
#define UNIQUE(v) do { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); } while (false)
#define f1(i,n) for(ll i=0;i<n;++i)
#define f2(i,k,n) for(int i=k;i<n;++i)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
      ll n,k,x;
      cin>>n>>k;
      set<ll> s;
      vector<ll> v1,v2,v3;
      f1(i,n){
          cin>>x;
          v1.pb(x);
      }
      ll len=0;
      f2(i,1,n){
      len+=(v1[i]!=v1[i-1]);
      }
     if(k==1){
        if(s.size()==1)cout<<1<<endl;
        else cout<<-1<<endl;
     }
     else cout<<ceil(len/(k-1))<<endl;
    }

}


#include <bits/stdc++.h>  // modifying on 18th Nov,2019 10:34am
using namespace std;

#define max_size 1000005
#define pb push_back
#define mp make_pair
#define ft first

#define sd second
#define ll long long
#define inf 1000000007
#define ll_max 1e18

#define bitcount(a) __builtin_popcountll(a)   // count set bits
#define lzcount(x) __builtin_clz(x)        // count leading zeros in binary representation of number
#define tzcount(x) __builtin_ctz(x)        // count trailing zeros in binary representation of number
#define digit(n) floor(log10(n)+1)
#define UNIQUE(v) do { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); } while (false)
#define f1(i,n) for(ll i=0;i<n;++i)
#define f2(i,k,n) for(int i=k;i<n;++i)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
      ll n,k,x;
      cin>>n>>k;
      set<ll> s;
      vector<ll> v1,v2,v3;
      f1(i,n){
          cin>>x;
          v1.pb(x);
          s.insert(x);
      }
      ll len=0;
      f2(i,1,n){
      len+=(v1[i]!=v1[i-1]);
      }
     if(k==1){
        if(s.size()==1)cout<<1<<endl;
        else cout<<-1<<endl;
     }

     else cout<<ceil(len/(k-1))<<endl;
    }

}


#include <bits/stdc++.h>  // modifying on 18th Nov,2019 10:34am
using namespace std;

#define max_size 1000005
#define pb push_back
#define mp make_pair
#define ft first

#define sd second
#define ll long long
#define inf 1000000007
#define ll_max 1e18

#define bitcount(a) __builtin_popcountll(a)   // count set bits
#define lzcount(x) __builtin_clz(x)        // count leading zeros in binary representation of number
#define tzcount(x) __builtin_ctz(x)        // count trailing zeros in binary representation of number
#define digit(n) floor(log10(n)+1)
#define UNIQUE(v) do { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); } while (false)
#define f1(i,n) for(ll i=0;i<n;++i)
#define f2(i,k,n) for(int i=k;i<n;++i)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
      ll n,k,x;
      cin>>n>>k;
      set<ll> s;
      vector<ll> v1,v2,v3;
      f1(i,n){
          cin>>x;
          v1.pb(x);
          s.insert(x);
      }
      ll len = s.size();
     if(k==1){
        if(s.size()==1)cout<<1<<endl;
        else cout<<-1<<endl;
     }
     else if(len <= k)cout<<1<<endl;
     else{
           len--;
           k--;
           ll ans=len/k;
           cout<<ans<<endl;
           if(len%k)ans++;
           cout<<ans<<endl;
        }

    }

}


#include <bits/stdc++.h>  // modifying on 18th Nov,2019 10:34am
using namespace std;

#define max_size 1000005
#define pb push_back
#define mp make_pair
#define ft first

#define sd second
#define ll long long unsigned int
#define inf 1000000007
#define ll_max 1e18

#define bitcount(a) __builtin_popcountll(a)   // count set bits
#define lzcount(x) __builtin_clz(x)        // count leading zeros in binary representation of number
#define tzcount(x) __builtin_ctz(x)        // count trailing zeros in binary representation of number
#define digit(n) floor(log10(n)+1)
#define UNIQUE(v) do { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); } while (false)
#define f1(i,n) for(ll i=0;i<n;++i)
#define f2(i,k,n) for(int i=k;i<n;++i)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
      ll n,k,x;
      cin>>n>>k;
      set<ll> s;
      vector<ll> v1,v2,v3;
      f1(i,n){
          cin>>x;
          v1.pb(x);
          s.insert(x);
      }
     if(s.size()==k)cout<<1<<endl;
     else if(ceil((s.size()+1)/2 + (s.size()+1)%2) <=k )cout<<2<<endl;
     else cout<<-1<<endl;
    }

}


#include <bits/stdc++.h>  // modifying on 18th Nov,2019 10:34am
using namespace std;

#define max_size 1000005
#define pb push_back
#define mp make_pair
#define ft first

#define sd second
#define ll long long
#define inf 1000000007
#define ll_max 1e18

#define bitcount(a) __builtin_popcountll(a)   // count set bits
#define lzcount(x) __builtin_clz(x)        // count leading zeros in binary representation of number
#define tzcount(x) __builtin_ctz(x)        // count trailing zeros in binary representation of number
#define digit(n) floor(log10(n)+1)
#define UNIQUE(v) do { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); } while (false)
#define f1(i,n) for(ll i=0;i<n;++i)
#define f2(i,k,n) for(int i=k;i<n;++i)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
      ll n,k,x;
      cin>>n>>k;
      set<ll> s;
      vector<ll> v1,v2,v3;
      f1(i,n){
          cin>>x;
          v1.pb(x);
          s.insert(x);
      }

     if(s.size()==k)cout<<1<<endl;
     else if(s.size()!=1 && k==1)cout<<-1<<endl;
     else cout<<(s.size()-1+k-2)/(k-1)<<endl;
    }

}


n=int(input())
l=list(map(int,input().split()))
s=list(set(l))
a=len(s)
scores=0
for i in range(a):
    s[i]=[s[i],l.count(s[i])*s[i]]
t=[[[],[]] for i in range(a)]
t[0][0].append(0)
t[0][1].append(s[0][1])
for j in range(1,a):
    t[j][0]+=t[j-1][0]
    t[j][0]+=t[j-1][1]
    for k in t[j-1][0]:
        t[j][1]+=[k+s[j][1]]
    if s[j-1][0]!=s[j][0]-1:
        for k in t[j-1][1]:
            t[j][1]+=[k+s[j][1]]
for i in range(2):
    for k in t[a-1][i]:
        scores=max(scores,k)
print(scores)


def M(x):
    if x==0 or x==1:return s[x]
    else:
        return max(M(x-1),M(x-2)+s[x])
input()
s=[0]*100001
for i in [int(a) for a in input().split()]:
    s[i]+=i
for k in range(100000,1,-1):
    if s[k]!=0:
        print(M(k))
        break


input()
l=list(map(int,input().split()))
s=list(set(l))
sc=0
while s!=[]:
    a=len(s)
    for i in range(a):
        s[i]=[s[i],l.count(s[i])*s[i],l.count(s[i])*s[i]]
    for i in range(a):
        if i==0:pass
        elif s[i-1][0]==s[i][0]-1:
            s[i][2]-=s[i-1][1]
        if i==a-1:pass
        elif s[i+1][0]==s[i][0]+1:
            s[i][2]-=s[i+1][1]
    x=0
    scm=s[0][2]
    for i in range(1,a):
        if s[i][2]>scm:
            scm=s[i][2]
            x=i
    sc+=s[x][1]
    s[x][1]=0
    if x==0:pass
    elif s[x-1][0]==s[x][0]-1:
        s[x-1][1]=0
    if x==a-1:pass
    elif s[x+1][0]==s[x][0]+1:
        s[x+1][1]=0
    while True:
        t=1
        for j in range(len(s)):
            if s[j][1]==0:
                del s[j]
                t=0
                break
        if t==1:
            break
print(sc)


input()
s=[0]*100001
for i in [int(a) for a in input().split()]:
    s[i]+=i
for i in range(2,100001):
    s[i]=max(s[i-1],s[i-2]+s[i])
print(s[-1])


input()
l=[int(i) for i in input().split()]
s=list(set(l))
a=len(s)
scores=0
for i in range(a):
    s[i]=[s[i],l.count(s[i])*s[i]]
A=[[] for i in range(a)]
A[0]+=[[0 for i in range(a)],[1]+[0 for i in range(a-1)]]
for i in range(1,a):
    A[i]+=A[i-1]
    if s[i-1][0]!=s[i][0]-1:
        for j in range(len(A[i-1])):
            b=[]
            b+=A[i-1][j]
            b[i]=1
            A[i]+=[b]
    else:
        for j in range(len(A[i-1])):
            if A[i-1][j][i-1]==0:
                b=[]
                b+=A[i-1][j]
                b[i]=1
                A[i]+=[b]
sc=[]
for j in A[a-1]:
    sc.append(sum(j[k]*s[k][1] for k in range(a)))
scores=max(k for k in sc)
print(scores)


input()
l=[int(i) for i in input().split()]
s=list(set(l))
a=len(s)
scores=0
for i in range(a):
    s[i]=[s[i],l.count(s[i])*s[i]]
A=[[] for i in range(a)]
A[0]+=[[0 for i in range(a)],[1]+[0 for i in range(a-1)]]
for i in range(1,a):
    A[i]+=A[i-1]
    if s[i-1][0]!=s[i][0]-1:
        for j in range(len(A[i-1])):
            A[i-1][j][i]=1
            A[i]+=[A[i-1][j]]
    else:
        for j in range(len(A[i-1])):
            if A[i-1][j][i-1]==0:
                A[i-1][j][i]=1
                A[i]+=[A[i-1][j]]
sc=[]
for j in A[a-1]:
    sc.append(sum(j[k]*s[k][1] for k in range(a)))
scores=max(k for k in sc)
print(scores)


n = int(input())
line = input()
line = [int(i) for i in line.split()]
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    s = list(s)
    m = [i * line.count(i) for i in s]
    n = max(s)
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
    c[1] = m[1]
    u[1] = m[0]
    for i in range(2,n):
        c[i] = max(c[i - 2],u[i - 2]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


n = int(input())
line = input()
line = [int(i) for i in line.split()]
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    n = max(s)
    m = [i * line.count(i) for i in range(1,n + 1)]
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
    c[1] = m[1]
    u[1] = m[0]
    for i in range(2,n):
        c[i] = max(c[i - 2],u[i - 2]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


n = int(input())
line = input()
line = [int(i) for i in line.split()]
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    s = list(s)
    m = [i * line.count(i) for i in s]
    n = len(s)
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
    if s[1] - s[0] == 1:
        c[1] = m[1]
        u[1] = m[0]
    else:
        c[1] += m[1]
        u[1] = m[0]
    for i in range(2,n):
        if s[i] - s[i - 1] == 1:
            c[i] = max(c[i - 2],u[i - 2]) + m[i]
        else:
            c[i] = max(c[i - 1],u[i - 1]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


n = int(input())
line = list(map(int,input().split()))
n = max(line)
m = [[0 for i in range(n)]]
for i in range(len(line)):
    m[0][line[i] - 1] += 1
m.append([m[0][0] for i in range(n)])
m.append([0 for i in range(n)])
for i in range(1,n):
    m[1][i] = m[2][i - 1] + m[0][i]
    m[2][i] = max(m[1][i - 1],m[2][i - 1])
print(max(m[1][n - 1],m[2][n - 1]))


n = int(input())
line = list(map(int,input().split()))
n = max(line)
m = [[i * line.count(i) for i in range(1,n + 1)]]
m.append([m[0][0] for i in range(n)])
m.append([0 for i in range(n)])
for i in range(1,n):
    m[1][i] = m[2][i - 1] + m[0][i]
    m[2][i] = max(m[1][i - 1],m[2][i - 1])
print(max(m[1][n - 1],m[2][n - 1]))


n = int(input())
line = input()
line = [int(i) for i in line.split()]
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    s = list(s)
    m = [i * line.count(i) for i in s]
    n = len(s)
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
    c[1] = m[1]
    u[1] = m[0]
    for i in range(2,n):
        c[i] = max(c[i - 2],u[i - 2]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


n = int(input())
line = input()
line = list(map(int,line.split()))
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    n = max(s)
    m = [i * line.count(i) for i in range(1,n + 1)]
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
    c[1] = m[1]
    u[1] = m[0]
    for i in range(2,n):
        c[i] = max(c[i - 2],u[i - 2]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


n = int(input())
line = input()
line = list(map(int,line.split()))
line.sort()
s = set(line)
n = max(s)
m = [i * line.count(i) for i in range(1,n + 1)]
c = [m[0] for i in range(n)]
u = [0 for i in range(n)]
for i in range(1,n):
    c[i] = u[i - 1] + m[i]
    u[i] = max(c[i - 1],u[i - 1])
print(max(c[n - 1],u[n - 1]))


n = int(input())
line = input()
line = [int(i) for i in line.split()]
if n == 1:
    print(line[0])
else:
    line.sort()
    s = set(line)
    s = list(s)
    m = [i * line.count(i) for i in s]
    n = len(s)
    c = [m[0] for i in range(n)]
    u = [0 for i in range(n)]
        c[1] = m[1]
        u[1] = m[0]
    for i in range(2,n):
        c[i] = max(c[i - 2],u[i - 2]) + m[i]
        u[i] = max(c[i - 1],u[i - 1])
    print(max(c[n - 1],u[n - 1]))


q=int(input())
w=list(map(int,input().split()))
e=list(set(w))
k=0
r=[0]*(max(w)+2)
for i in e:
    r[i]=i*w.count(i)
while sum(r)!=0:
    k+=max(max(r),r[r.index(max(r))-1]+r[r.index(max(r))+1])
    if max(r)==max(max(r),r[r.index(max(r))-1]+r[r.index(max(r))+1]):
        p=r.index(max(r))
        r[p]=0
        r[p+1]=0
        r[p-1]=0
    else:
        p=r.index(max(r))
        r[p]=0
        r[p+1]=0
        r[p-1]=0
        r[p+2]=0
        r[p-2]=0
print(k)


q=int(input())
w=list(map(int,input().split()))
e=list(set(w))
k=0
r=[0]*(len(e)+2)
for i in e:
    r[i]=i*w.count(i)
while sum(r)!=0:
    k+=max(r)
    p=r.index(max(r))
    r[p]=0
    r[p+1]=0
    r[p-1]=0
print(k)


q=int(input())
w=list(map(int,input().split()))
e=list(set(w))
k=0
r=[0]*(max(w)+2)
for i in e:
    r[i]=i*w.count(i)
while sum(r)!=0:
    k+=max(r)
    p=r.index(max(r))
    r[p]=0
    r[p+1]=0
    r[p-1]=0
print(k)


n=int(input())
q=list(map(int,input().split()))
dp=[0]*100002
e=0
for i in range(1,n+1):
    dp[i]=q.count(i)*i
w=max(dp)
while w:
    e+=w
    k=dp.index(w)
    dp[k]=dp[k+1]=dp[k-1]=0
    w=max(dp)
print(e)


n=int(input())
q=list(map(int,input().split()))
dp=[0]*100001
for i in q:
    dp[i]+=i
a=b=0
for i in dp:
    a,b=max(a,b+i),a
print(a)


n=int(input())
q=list(map(int,input().split()))
dp=[0]*100002
e=0
for i in range(1,n+1):
    dp[i]=q.count(i)*i
a=b=0
for i in dp:
    a,b=max(a,b+i),a
print(a)


n=int(input())
q=list(map(int,input().split()))
dp=[0]*100002
e=0
for i in range(1,n+1):
    dp[i]=q.count(i)*i
for i in range(0,n+1,2):
    e+=dp[i]
print(max(e,sum(dp)-e))


n = int(input())
numbers = list(map(int, input().split()))
cnt = [0] * (10**5 + 1)
for x in numbers:
    cnt[x] += 1

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

m = max(numbers)
print(f(m))


n = int(input())
numbers = list(map(int, input().split()))

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

m = max(numbers)
def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = numbers.count(1)
    else:
        result = max(f(n - 1), f(n - 2) + numbers.count(n) * n)

    dic[n] = result
    return result

print(f(m))


n = int(input())
numbers = list(map(int, input().split()))
cnt = [0] * 10**5
for x in numbers:
    cnt[x] += 1

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

m = max(numbers)
print(f(m))


n = int(input())
numbers = list(map(int, input().split()))

cnt = [0] * (10 ** 5 + 1)
for i in numbers:
    cnt[i] += 1

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        x1 = f(n - 1)
        x2 = f(n - 2) + cnt[n] * n
        result = max(x1, x2)

    dic[n] = result
    return result

m = max(numbers)
print(f(n))


n = int(input())
numbers = list(map(int, input().split()))
cnt = [0] * 10**5
for x in numbers:
    cnt[x] = numbers.count(x)

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

m = max(numbers)
print(f(m))


n = int(input())
numbers = list(map(int, input().split()))
numbers.sort()
cnt = [numbers.count(i) for i in range(n + 1)]

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

print(f(numbers[::-1][0]))


n = int(input())
numbers = list(map(int, input().split()))
cnt = [0] * 10**5 + 1
for x in numbers:
    cnt[x] += 1

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

m = max(numbers)
print(f(m))


n = int(input())
numbers = list(map(int, input().split()))
cnt = [0] * (n + 1)
for x in numbers:
    cnt[x] = numbers.count(x)

# numbers = [1, 2, 2, 2, 3, 3, 4]
# cnt = [0, 1, 3, 2, 1]
#        0, 1, 2, 3, 4

dic = {}

m = max(numbers)

def f(n):
    if n in dic:
        return dic[n]
    if n == 0:
        result = 0
    elif n == 1:
        result = cnt[1]
    else:
        result = max(f(n - 1), f(n - 2) + cnt[n] * n)

    dic[n] = result
    return result

print(f(m))


n = int(input())
numbers = list(map(int, input().split()))

cnt = [0] * (10 ** 5 + 1)
for i in numbers:
    cnt[i] += 1

def f(n):
    x = [0, cnt[1]]
    for i in range(2, n+1):
        x.append(max(x[i - 1], x[i - 2] + cnt[i] * i))

    return x[::-1][0]

m = max(numbers)
print(f(m))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])

def getMaxScore(keys):

    saved = [0]

    cur_key_chain = []
    last_num = None
    for key in keys:
        cur_key_chain.append(key)
        if last_num is not None and last_num + 1 == key:
            saved.append(max((key * nums_counter[key]) + saved[len(saved) - 2], saved[len(saved) - 1]))
        else:
            saved.append(key * nums_counter[key] + saved[len(saved) - 1])

        last_num = key

    return(saved[len(saved) - 1])

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))

def getMaxScore(keys):
    #print(len(keys))
    if len(keys) == 0:
        score = 0
    elif len(keys) == 1:
        score = nums_counter[keys[0]] * keys[0]
    else:
        all_scores = []
        #print(keys)
        for key in keys:
            s = nums_counter[key] * key
            remaining_keys = [k for k in keys if abs(k - key) > 1 ]
            all_scores.append(s + getMaxScore(remaining_keys))
        score = max(all_scores)
    return score

print(getMaxScore(list(nums_counter.keys())))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])

def getMaxScore(keys):

    saved = [0]

    cur_key_chain = []
    last_num = None
    for key in keys:
        cur_key_chain.append(key)
        if last_num + 1 == key:
            saved.append(max((key * nums_counter[key]) + saved[len(saved) - 2], saved[len(saved) - 1]))
        else:
            saved.append(key * nums_counter[key] + saved[len(saved) - 1])

        last_num = key

    return(saved[len(saved) - 1])

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}

def getMaxScore(keys):
    #print(len(keys))
    if len(keys) == 0:
        score = 0
    elif len(keys) == 1:
        score = nums_counter[keys[0]] * keys[0]
    elif tuple(keys) in saved:
        score = saved[tuple]
    else:
        all_scores = []
        #print(keys)
        for key in keys:
            s = nums_counter[key] * key
            remaining_keys = [k for k in keys if abs(k - key) > 1 ]
            all_scores.append(s + getMaxScore(remaining_keys))
        score = max(all_scores)

    saved[tuple(keys)] = score

    return score

print(getMaxScore(list(nums_counter.keys())))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}
calls = 0

def getMaxScore(keys):
    global calls
    calls += 1
    #print(len(keys))
    if tuple(keys) in saved:
        #print('***ACCESSING SAVED***' + ' ' +  str(keys))
        score = saved[tuple(keys)]
    elif len(keys) == 0:
        score = 0
    else:
        all_scores = []
        #print(keys)
        key = list(keys)[0]

        if key + 1 in keys:
            s = nums_counter[key + 1] * (key + 1)
            remain_keys = keys - set([key, key + 1, key + 2])
            all_scores.append(s + getMaxScore(remain_keys))
        if key - 1 in keys:
            s = nums_counter[key - 1] * (key - 1)
            remain_keys = keys - set([key - 2, key - 1, key])
            all_scores.append(s + getMaxScore(remain_keys))

        s = nums_counter[key] * (key)
        remain_keys = keys - set([key - 1, key, key + 1])
        all_scores.append(s + getMaxScore(remain_keys))
        score = max(all_scores)

    saved[tuple(keys)] = score

    return score

#keys = :

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}

def getMaxScore(keys):
    #print(len(keys))
    if len(keys) == 0:
        score = 0
    elif len(keys) == 1:
        score = nums_counter[keys[0]] * keys[0]
    elif tuple(keys) in saved:
        score = saved[tuple(keys)]
    else:
        all_scores = []
        #print(keys)
        for key in keys:
            s = nums_counter[key] * key
            remaining_keys = [k for k in keys if abs(k - key) > 1 ]
            all_scores.append(s + getMaxScore(remaining_keys))
        score = max(all_scores)

    saved[tuple(keys)] = score

    return score

print(getMaxScore(list(nums_counter.keys())))


from collections import Counter
from collections import defaultdict

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))

def getMaxScore(keys):

    saved = [0]

    cur_key_chain = []
    for key in keys:
        cur_key_chain.append(key)
        if key - 1 in cur_key_chain:
#             no_prev_elem = list(old_key_chain)
#             no_prev_elem.remove(key - 1)
#
#             prev_value = saved[tuple(no_prev_elem)] if tuple(no_prev_elem) in saved else 0

            #print(cur_key_chain)
            #print(saved)
            #print('Choosing between ' + str((key * nums_counter[key]) + prev_value) + ' and ' + str(saved[tuple(old_key_chain)]))

            saved.append(max((key * nums_counter[key]) + saved[len(saved) - 2], saved[len(saved) - 1]))
        else:
            saved.append(key * nums_counter[key] + saved[len(saved) - 1])

    return(saved[len(saved) - 1])

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])

def getMaxScore(keys):

    saved = [0]
    cur_key_chain = []
    last_num = None
    for key in keys:
        cur_key_chain.append(key)
        if last_num is not None and last_num + 1 == key:
            saved.append(max((key * nums_counter[key]) + saved[len(saved) - 2], saved[len(saved) - 1]))
        else:
            saved.append(key * nums_counter[key] + saved[len(saved) - 1])

        last_num = key

    return(saved[len(saved) - 1])

print(getMaxScore(sorted(list(nums_counter.keys()))))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}
keys = list(nums_counter.keys())

def getMaxScore(keys):

    #print(len(keys))

    cur_key_chain = []
    for key in keys:
        old_key_chain = cur_key_chain[:]
        cur_key_chain.append(key)

        if len(cur_key_chain) == 1:
            saved[tuple(cur_key_chain)] = key * nums_counter[key]
        elif key - 1 in cur_key_chain:
            no_prev_elem = list(old_key_chain)
            no_prev_elem.remove(key - 1)

            prev_value = saved[tuple(no_prev_elem)] if tuple(no_prev_elem) in saved else 0

            #print(cur_key_chain)
            #print(saved)
            #print('Choosing between ' + str((key * nums_counter[key]) + prev_value) + ' and ' + str(saved[tuple(old_key_chain)]))

            saved[tuple(cur_key_chain)] = max((key * nums_counter[key]) + prev_value, saved[tuple(old_key_chain)])
        else:
            saved[tuple(cur_key_chain)] = key * nums_counter[key] + saved[tuple(old_key_chain)]

    return(saved[tuple(keys)])

print(getMaxScore(nums_counter.keys()))


from collections import Counter
from sys import setrecursionlimit
setrecursionlimit(100000)

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}
calls = 0

def getMaxScore(keys):
    global calls
    calls += 1
    #print(len(keys))
    if tuple(keys) in saved:
        #print('***ACCESSING SAVED***' + ' ' +  str(keys))
        score = saved[tuple(keys)]
    elif len(keys) == 0:
        score = 0
    else:
        all_scores = []
        #print(keys)
        key = list(keys)[0]

        if key + 1 in keys:
            s = nums_counter[key + 1] * (key + 1)
            remain_keys = keys - set([key, key + 1, key + 2])
            all_scores.append(s + getMaxScore(remain_keys))
        if key - 1 in keys:
            s = nums_counter[key - 1] * (key - 1)
            remain_keys = keys - set([key - 2, key - 1, key])
            all_scores.append(s + getMaxScore(remain_keys))

        s = nums_counter[key] * (key)
        remain_keys = keys - set([key - 1, key, key + 1])
        all_scores.append(s + getMaxScore(remain_keys))
        score = max(all_scores)

    saved[tuple(keys)] = score

    return score

#keys = :

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])
#print(nums_counter)
#print(list(nums_counter.keys()))
saved = {}

def getMaxScore(keys):
    #print(len(keys))
    if tuple(keys) in saved:
        score = saved[tuple(keys)]
    elif len(keys) == 0:
        score = 0
    else:
        all_scores = []
        #print(keys)
        for key in keys:
            s = nums_counter[key] * key
            remaining_keys = keys - set([key -1, key, key+1])
            all_scores.append(s + getMaxScore(remaining_keys))
        score = max(all_scores)

    saved[tuple(keys)] = score

    return score

print(getMaxScore(nums_counter.keys()))


from collections import Counter

in_n = input()
in_nums= input()

n = int(in_n)
nums_counter = Counter([int(x) for x in in_nums.split()])

def getMaxScore(keys):

    saved = [0]
    print(keys)
    cur_key_chain = []
    last_num = None
    for key in keys:
        cur_key_chain.append(key)
        if last_num is not None and last_num + 1 == key:
            saved.append(max((key * nums_counter[key]) + saved[len(saved) - 2], saved[len(saved) - 1]))
        else:
            saved.append(key * nums_counter[key] + saved[len(saved) - 1])

        last_num = key

    return(saved[len(saved) - 1])

print(getMaxScore(sorted(list(nums_counter.keys()))))


n=int(input())
x=[int(i) for i in input().split()]
c=max(x)+1
z=[0]*c
for i in range(n):
    z[x[i]]+=1
d=[0]*(c)
d[1]=z[1]
for i in range(2,c):
    d[i]=max(d[i-1],d[i-2]+z[i]*i)
print(d[c-1])


n=int(input())
a=list(map(int,input().split()))
m=max(a)+1
x,y=0,0
for i in range(1,m):
    x,y=max(x,y),x+i*a.count(i)
x=max(x,y)
print(x)


def pau(x):
    if x==0:return 0
    if x==1:return z[0]
    else: return max(pau(x-2)+z[x-1],pau(x-1))
n=int(input())
x=[int(i) for i in input().split()]
x.sort()
y=[]
z=[]
for i in x:
    if i not in y:
        y.append(i)
for i in range(1,max(y)+1):
    z.append(i*x.count(i))
print(pau(i))


def pau(x):
    return paul(0,0,0,x)
def paul(ans1,ans2,c,max):
    if c>=max:return ans2
    if ans1+z[c]>ans2:
        return paul(ans2,ans1+z[c],c+1,max)
    else:
        return paul(ans2,ans2,c+1,max)
n=int(input())
x=[int(i) for i in input().split()]
x.sort()
z=[]
c=max(x)
for i in range(1,c+1):
    z.append(i*x.count(i))
print(pau(c))


def pau(x):
    if x==0:return 0
    if x==1:return z[0]
    else: return max(pau(x-2)+z[x-1],pau(x-1))
n=int(input())
x=[int(i) for i in input().split()]
x.sort()
y=[]
z=[]
for i in range(1,max(x)+1):
    z.append(i*x.count(i))
print(pau(i))


def pau(x):
    if x==0:return 0
    if x==1:return z[0]
    else: return max(pau(x-2)+z[x-1],pau(x-1))
n=int(input())
x=[int(i) for i in input().split()]
x.sort()
y=[]
z=[]
for i in x:
    if i not in y:
        y.append(i)
for i in y:
    z.append(i*x.count(i))
print(pau(len(z)))


n=int(input())
x=[int(i) for i in input().split()]
x.sort()
z=[]
c=max(x)
for i in range(c+1):
    z.append(i*x.count(i))
d=[0]*(c+1)
d[1]=z[1]
for i in range(2,c+1):
    d[i]=max(d[i-1],d[i-2]+z[i])
print(d[c])


n=int(input())
a=list(map(int,input().split()))
b=[0]*100001
for i in a:
    b[i]+=i
x,y=0,0
for i in range(1,100001):
    x,y=max(x,y),x+b[i]
x=max(x,y)
print(x)


n=int(input())
x=[int(i) for i in input().split()]
x.sort()
c=max(x)+1
z=[0]*c
for i in range(n):
    z[x[i]]+=1
d=[0]*(c)
d[1]=z[1]
for i in range(2,c):
    d[i]=max(d[i-1],d[i-2]+z[i]*i)
print(d[c-1])


n=int(input())
x=[int(i) for i in input().split()]
x.sort()
c=max(x)+1
z=[0]*c
for i in range(n):
    z[x[i]]+=1
print(z)
d=[0]*(c)
d[1]=z[1]
for i in range(2,c):
    d[i]=max(d[i-1],d[i-2]+z[i]*i)
print(d[c-1])


n=int(input())
x=[int(i) for i in input().split()]
x.sort()
z=[]
c=max(x)
for i in range(c+1):
    z.append(x.count(i))
d=[0]*(c+1)
d[1]=z[1]
for i in range(2,c+1):
    d[i]=max(d[i-1],d[i-2]+z[i]*i)
print(d[c])


n = int(input())
a = list(map(int, input().split()))

l = []
for i in set(a):
      l.append([i])

for i in set(a):
    for j in range(len(l)):
        flag = True
        for x in range(len(l[j])):
            if i == l[j][x] or i == l[j][x] - 1 or i == l[j][x] + 1:
                flag = False
        if flag == True:
            l[j] += [i]

max_score = 0
for i in range (len(l)):
    score = 0
    for j in range (len(l[i])):
        score += a.count(l[i][j]) * l[i][j]
    if max_score < score:
        max_score = score

print(max_score)


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [l[sorted(set(a))[0]]]
d.append(l[sorted(set(a))[1]])
last = sorted(set(a))[1]
for i in sorted(set(a))[2:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    last = i

print(d[len(d) - 1])


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [0]
d.append(l[sorted(set(a))[0]])
last = sorted(set(a))[0]
for i in sorted(set(a))[1:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    last = i
print(d[len(d) - 1])


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [0]
sort_a = sorted(set(a))
d.append(l[sort_a[0]])
last = sort_a[0]

for i in sort_a[1:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    else: d.append(d[len(d) - 1] + l[i])
    last = i
print(d[len(d) - 1])


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [l[sorted(set(a))[0]]]
last = sorted(set(a))[1]
for i in sorted(set(a))[1:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    last = i
print(d[len(d) - 1])


l = []
for i in set(a):
      l.append([i])

for i in set(a):
    for j in range(len(l)):
        flag = True
        for x in range(len(l[j])):
            if i == l[j][x] or i == l[j][x] - 1 or i == l[j][x] + 1:
                flag = False
        if flag == True:
            l[j] += [i]

max_score = 0
for i in range (len(l)):
    score = 0
    for j in range (len(l[i])):
        score += a.count(l[i][j]) * l[i][j]
    if max_score < score:
        max_score = score

print(max_score)


n = int(input())
a = list(map(int, input().split()))
max_score = 0
for i in set(a):
    score = sum(a)
    if i - 1 in a:
        score -= (i - 1) * a.count(i-1)
    if i + 1 in a:
        score -= (i + 1) * a.count(i+1)
    if score > max_score:
        max_score = score
print(max_score)


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [l[sorted(set(a))[0]]]
d.append(l[sorted(set(a))[1]])

for i in sorted(set(a))[2:]:
    d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))

print(d[len(d) - 1])


n = int(input())
a = list(map(int, input().split()))

l, d = [0] * 100001, []
temp_a = sorted(set(a))
for i in a:
    l[i] += 1

d.append(0)
d.append(temp_a[0] * l[temp_a[0]])

last = temp_a[0]
for i in temp_a[1:]:
    if last == i - 1:
        d.append(max(d[len(d)-1], d[len(d) -2] + i * l[i]))
    else: d.append(d[len(d)-1] + l[i] * i)
    last = i
print(d[len(d)-1])


n = int(input())
a = list(map(int, input().split()))

l = dict()
sort_a = sorted(set(a))

for i in sort_a:
    l[i] = a.count(i) * i

d = [0]
d.append(l[sort_a[0]])
last = sort_a[0]

for i in sort_a[1:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    else: d.append(d[len(d) - 1] + l[i])
    last = i

print(d[len(d) - 1])


n = int(input())
a = list(map(int, input().split()))

l = dict()

for i in set(a):
    l[i] = a.count(i) * i

d = [0]
d.append(l[sorted(set(a))[0]])
last = sorted(set(a))[0]
for i in sorted(set(a))[1:]:
    if last == i - 1:
        d.append(max(d[len(d) - 1], d[len(d) - 2] + l[i]))
    else: d.append(d[len(d) - 1] + l[i])
    last = i
print(d[len(d) - 1])


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in range (1,max(l)+1):
    if i not in l:
        continue
    o[i] = 0
    for j in l:
        if j!= i+1 and j!= i-1:
            o[i]+=j

print(max(o))


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)
k = []
for i in range (1,max(l)+1):
    for j in l:
        if i == j:
            o[i]+=j
_max = 0
for i in range (1,max(l)+1):
    j = i
    m = 0
    while j<max(l)+1:
        if o[j] != 0:
            m+=o[j]
            j+=2
        else:
            j+=1
    k.append(m)

print(max(k))


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)
k = [0]*(max(l)+1)
for i in range (1,max(l)+1):
    for j in l:
        if i == j:
            o[i]+=j

for i in range (1,len(o)):
    if o[i] == 0:
        continue
    else:
        if i%2 == 0:
            j = 2
        else:
            j = 1

        while j < len(o):
            k[i]+=o[j]
            j+=2

print(max(k))


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)
for i in range (1,max(l)+1):
    for j in l:
        if i == j:
            o[i]+=j

if o.index(max(o)) % 2 == 0:
    j = 2
else:
    j = 1
_max = 0
for i in range (j,len(o),1):
    if o[i] != 0 and i!=j+1 and i!= j-1:
        _max+=o[i]
        j+=2

print(_max)


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in range (1,max(l)+1):
    for j in l:
        if i == j:
            o[i]+=j

for i in range (2,len(o)):
    if o[i] + o[i-2] > o[i-1]:
        o[i] = o[i] + o[i-2]
    else:
        o[i] = o[i-1]

print(o[len(o)-1])


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in range (1,max(l)+1):
    o[i] = 0
    for j in l:
        if j!= i+1 and j!= i-1:
            o[i]+=j

print(max(o))


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in range (1,max(l)+1):
    for j in l:
        if i == j:
            o[i]+=j
_max = 0
for i in range (1,max(l)+1):
    j = 1
    k = 0
    while j<max(l)+1:
        if o[j] != 0:
            k+=o[j]
            j+=2
        else:
            j+=1
    if k>_max:
        _max = k

print(_max)


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in range (1,max(l)+1):
    if i not in l:
        continue
    o[i] = 0
    for j in l:
        if j!= i+1 and j!= i-1:
            o[i]+=j

print(o)


n = int(input())
l = list(map(int,input().split()))
o = [0]*(max(l)+1)

for i in l:
    o[i]+=i

for i in range (2,len(o)):
    if o[i] + o[i-2] > o[i-1]:
        o[i] = o[i] + o[i-2]
    else:
        o[i] = o[i-1]

print(o[len(o)-1])


n = gets.to_i
a = gets.split.map(&:to_i).sort.reverse

#p a

prv = 1e6
score = 0
n.times do
    x = a.shift
    if x < prv - 1
        score += x
        prv = x
    end
end

puts score


n = gets.to_i
a = gets.split.map(&:to_i)

cnt = Array.new(1e5+5,0)
a.map{|x| cnt[x]+=1}

dp = Array.new(1e5+5,0)

i = 1
hi2 = 0
(dp.length-2).times do
    i += 1
    hi2 = [hi2,dp[i-2]].max
    dp[i] = i * cnt[i] + hi2
end

puts dp.max


n = gets.to_i
a = gets.split.map(&:to_i)

cnt = Array.new(1e5+5,0)
a.map{|x| cnt[x]+=1}

dp = Array.new(1e5+5,0)

i = 1
hi2 = 0
dp[1] = cnt[1]
(dp.length-2).times do
    i += 1
    hi2 = [hi2,dp[i-2]].max
    dp[i] = i * cnt[i] + hi2
end

puts dp.max


# Author : Fuad Ashraful Mehmet
#Date: 18th April

n=gets.to_i
a=gets.split.map(&:to_i)
c=Array.new(a.max+1,0)

for i in 0...a.size
    c[a[i]]+=a[i]

end

dp=Array.new(c.size,0)
dp[1]=c[1]

for i in 2...c.size
    dp[i]=[dp[i-2]+c[i],dp[i-1]].max

end

puts dp[c.size-1]


n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = [r[i-1], rw[i-1]].max
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += k*h[k]
  end
end

puts [r.last, rw.last].max


n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = r[i-1]
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += + k*h[k]
  end
end

puts [r[keys.last], rw[keys.last]].max


n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
r = n.times.map{ 0 }

keys = h.keys.push(0).sort
keys.each_with_index do |k, i|
  r[i] = r[i-1]
  prev_key = keys[i-1]
  prev_score = h[prev_key]*prev_key
  score = h[k]*k
  if prev_key == k-1
    if score > prev_score
      r[i] += score - prev_score
      if keys[i-1] == keys[i-2] + 1
        r[i]+= r[i-2]
      end
    end
  else
    r[i] += h[k]*k
  end
end

puts r[keys.last]


n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = r[i-1]
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += + k*h[k]
  end
end

puts [r.last, rw.last].max


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency
results = []
results[0] = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    results[1] = results[0] + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    results[1] = second_sum > results[0] ? second_sum : results[0]
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    results[i] = results[i - 1] + uniq_array[i] * frequency[uniq_array[i]]
  elsif results[i - 1] > uniq_array[i] * frequency[uniq_array[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  uniq_array[i] * frequency[uniq_array[i]] + results[i - 2]
  end
  i += 1
end
puts results.last


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
arr.uniq!
# p arr
# p frequency
results = []
results[0] = arr[0] * frequency[arr[0]]
if arr.length > 1 then
  second_sum = arr[1] * frequency[arr[1]]
  results[1] = second_sum > results[0] ? second_sum : results[0]
end
i = 2
while i < arr.length do
  if arr[i] - arr[i - 1] > 1 then
    results[i] = results[i - 1] + arr[i] * frequency[arr[i]]
  elsif results[i - 1] > arr[i] * frequency[arr[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  arr[i] * frequency[arr[i]] + results[i - 2]
  end
  i += 1
end
puts results.last


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
arr.uniq!
# p arr
# p frequency
results = []
results[0] = arr[0] * frequency[arr[0]]
results[1] = arr[1] * frequency[arr[1]] if arr.length > 1
i = 2
while i < arr.length do
  if arr[i] - arr[i - 1] > 1 then
    results[i] = results[i - 1] + arr[i] * frequency[arr[i]]
  elsif results[i - 1] > arr[i] * frequency[arr[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  arr[i] * frequency[arr[i]] + results[i - 2]
  end
  i += 1
end
puts results.last


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    current = current + uniq_array[i] * frequency[uniq_array[i]]
  elsif current <= uniq_array[i] * frequency[uniq_array[i]] + prev then
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
  end
  i += 1
end
puts current


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    prev = current
    current += uniq_array[i] * frequency[uniq_array[i]]
  elsif current < uniq_array[i] * frequency[uniq_array[i]] + prev then
    temp = current
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
    prev = temp
  else
    prev = current
  end
  i += 1
end
puts current


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
else
  current = prev
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    prev = current
    current += uniq_array[i] * frequency[uniq_array[i]]
  elsif current < uniq_array[i] * frequency[uniq_array[i]] + prev then
    temp = current
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
    prev = temp
  else
    prev = current
  end
  i += 1
end
puts current


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
arr.uniq!
# p arr
# p frequency
results = []
results[0] = arr[0] * frequency[arr[0]]
if arr.length > 1 then
  if arr[1] - arr[0] > 1 then
    results[1] = results[0] + arr[1] * frequency[arr[1]]
  else
    second_sum = arr[1] * frequency[arr[1]]
    results[1] = second_sum > results[0] ? second_sum : results[0]
  end
end
i = 2
while i < arr.length do
  if arr[i] - arr[i - 1] > 1 then
    results[i] = results[i - 1] + arr[i] * frequency[arr[i]]
  elsif results[i - 1] > arr[i] * frequency[arr[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  arr[i] * frequency[arr[i]] + results[i - 2]
  end
  i += 1
end
puts results.last


n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
j = 1
uniq_array = []
uniq_array[0] = arr[0]
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
  end
  j += 1
end
# p uniq_array
# p frequency
results = []
results[0] = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    results[1] = results[0] + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    results[1] = second_sum > results[0] ? second_sum : results[0]
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    results[i] = results[i - 1] + uniq_array[i] * frequency[uniq_array[i]]
  elsif results[i - 1] > uniq_array[i] * frequency[uniq_array[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  uniq_array[i] * frequency[uniq_array[i]] + results[i - 2]
  end
  i += 1
end
puts results.last


n = gets.to_i
a = gets.split.map(&:to_i)
c = Array.new(a.max + 1, 0)
for i in 0...a.size
  c[a[i]] += a[i]
end

dp = Array.new(c.size, 0)
dp[1] = c[1]
for i in 2...c.size
  dp[i] = [dp[i - 2] + c[i], dp[i - 1]].max
end
puts dp[c.size - 1]


n = gets.to_i
arr = gets.split.map { |x| x.to_i }.sort
hash = Hash.new(0)
arr.each { |x| hash[x] += 1 }
hash = Hash[hash.sort_by { |key,value| value }]
sum = 0
while hash.size != 0
  temp = hash[hash.keys.last]
  sum += temp * hash.keys.last
  temp_key = hash.keys.last
  hash.delete(temp_key)
  hash.delete(temp_key - 1)
  hash.delete(temp_key + 1)
end
puts sum


def calc (mas)
  pairs = {}
  mas.each_index { |i| mas[i]= mas[i].to_i}
  cur = mas[0]
  count = 0
  mas.each do |x|
    if x==cur
      count += 1
    else
      pairs[cur] = count
      cur = x
      count = 1
    end
  end
  pairs[cur] = count
  pairs
end
n = gets.to_i
a = gets.split(" ")
a.sort_by! {|x| x.to_i}
b = calc(a)
best1 = 0
prev1 = -1
best2 = 0
b.each_pair {|x,y|
  new_best2 = [best1,best2].max
  if x!=prev1+1
    new_best1 = [best2, best1].max + x*y
  else
    new_best1 = best2 + x*y
  end
  prev1 = x
  best1 = new_best1
  best2 = new_best2
}
puts [best1,best2].max


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

int main(){
	ios::sync_with_stdio(0);
	int t;
	cin >> t;
	while (t--){
		int n, T, a, b;
		cin >> n >> T >> a >> b;
		vector<pair<int, int>> task(n, {0, 0});
		for (int i = 0; i < n; ++i){
			cin >> task[i].second;
		}
		for (int i = 0; i < n; ++i){
			cin >> task[i].first;
		}
		sort(task.begin(), task.end());
		int ans = 0;
		int time = (task[0].second ? b : a);
		for (int i = 1; i < n; ++i){
			if (task[i].first > time){
				ans++;
			}
			time += (task[i].second ? b : a);
		}
		ans += (time <= T);
		cout << ans << "\n";
	}

	cerr << clock() << "ms\n";
	return 0;
}


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

int main(){
	ios::sync_with_stdio(0);
	int t;
	cin >> t;
	while (t--){
		int n, T, a, b;
		cin >> n >> T >> a >> b;
		int cntA = 0, cntB = 0;
		vector<pair<int, int>> task(n, {0, 0});
		for (int i = 0; i < n; ++i){
			cin >> task[i].second;
			if (task[i].second){
				cntB++;
			}
			else{
				cntA++;
			}
		}
		for (int i = 0; i < n; ++i){
			cin >> task[i].first;
		}
		task.push_back({T + 1, 0});
		sort(task.begin(), task.end());
		int ans = 0;
		int cntx = 0, cnty = 0;
		for (int i = 0; i <= n; ++i){
			int use = cntx * a + cnty * b;
			int time = task[i].first - use - 1;
			if (time >= 0){
				int tA = min(cntA - cntx, time / a);
				time -= tA * a;
				int tB = min(cntB - cnty, time / b);
				ans = max(ans, cntx + cnty + tA + tB);
			}
			int now = i;
			while (now < task.size() && task[now].first == task[i].first){
				if (task[now].second){
					cnty++;
				}
				else{
					cntx++;
				}
				now++;
			}
			i = now - 1;
		}
		cout << ans << "\n";
	}

	cerr << clock() << "ms\n";
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
   // freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+1+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time));
      //  cout<<ans<<endl;
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=upper_bound(tim+1,tim+1+n,now)-tim;
            if(p<=(i+1)) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now-1;
                ans=max(ans,i+solve(res));
            }
        //    cout<<ans<<endl;
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
   // freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+1+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time)-1);
      //  cout<<ans<<endl;
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=upper_bound(tim+1,tim+1+n,now)-tim;
            if(p<=(i+1)) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now-1;
                ans=max(ans,i+solve(res));
            }
        //    cout<<ans<<endl;
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
    //freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time));
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=lower_bound(tim+1,tim+1+n,now)-tim;
            if(p<=i||(p==n+1&&i==n) ) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now-1;
                ans=max(ans,i+solve(res));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=1e3+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
  //  freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time));
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=lower_bound(tim+1,tim+1+n,now)-tim;
            if(p<=i||(p==n+1&&i==n) ) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now;
                ans=max(ans,i+solve(res));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
  //  freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+1+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time-1));
      //  cout<<ans<<endl;
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=upper_bound(tim+1,tim+1+n,now)-tim;
            if(p<=(i+1)) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now-1;
                ans=max(ans,i+solve(res));
            }
        //    cout<<ans<<endl;
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
    //freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+1+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time));
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=lower_bound(tim+1,tim+1+n,now)-tim;
            if(p<=i||(p==n+1&&i==n) ) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now-1;
                ans=max(ans,i+solve(res));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

const int maxn=2e5+10;
const int mod=1000000000+7;
const double eps=1e-6;

int m,n,T,a,b,op,tim[maxn],hard,easy;
struct node{
    int cost,time;
    bool operator <(const node &b) const {
        if(time==b.time) return cost<b.cost;
        return time<b.time;
    }
}ex[maxn];

int solve(int res) {
    int tmp=0;
    tmp+=min(res/a,easy);
    if(res>=easy*a) tmp+=min((res-easy*a)/b,hard);
    return tmp;
}

int main() {
  //  freopen("test.txt","r",stdin);
    cin>>m;
    while(m--) {
        easy=0,hard=0;
        cin>>n>>T>>a>>b;
        for(int i=1;i<=n;i++) {
            cin>>op;
            if(op) {
                ex[i].cost=b;
                hard++;
            } else{
                ex[i].cost=a;
                easy++;
            }
        }
        for(int i=1;i<=n;i++) {
            cin>>ex[i].time;
        }
        sort(ex+1,ex+n);
        for(int i=1;i<=n;i++)
            tim[i]=ex[i].time;
        int ans=0;
        ans=max(ans,solve(ex[1].time));
      //  cout<<ans<<endl;
        for(int i=1,now=0;i<=n;i++) {
            now+=ex[i].cost;
            if(ex[i].cost==b) hard--;
            else easy--;
            if(now>T) break;
            int p=lower_bound(tim+1,tim+1+n,now)-tim;
            if(p<=i||(p==n+1&&i==n) ) {
                ans=max(ans,i);
                if(i==n) continue;
                int res=tim[i+1]-now;
                ans=max(ans,i+solve(res));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

/*
10
3 5 1 3
0 0 1
2 1 4

2 5 2 3
1 0
3 2

1 20 2 4
0
16

6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6

4 16 3 6
1 0 1 1
8 3 5 6

6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17

7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10

6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12

5 17 2 5
1 1 1 1 0
17 11 10 6 4

1 1 1 2
0
1
*/


// ------------ My Template Start ------------ //
#include<bits/stdc++.h>
using namespace std;
#define fastaf ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long int
#define ull unsigned long long
#define vll vector<ll>
#define it(a) a.begin(),a.end()
#define pb push_back
#define ub(a,x) upper_bound(a.begin(),a.end(),x)
#define lb(a,x) lower_bound(a.begin(),a.end(),x)
#define bs(a,x) binary_search(a.begin(),a.end(),x)
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second
#define tll tuple<ll,ll,ll>
#define mt make_tuple
#define INF LONG_LONG_MAX
#define MOD 1000000007
#define mod 998244353
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define cases ll t; cin>>t; while(t--)
#define array(a,n) ll n; cin>>n; ll a[n]; rep(i,0,n) cin>>a[i];
#define vector(a,n) ll n; cin>>n; vll a(n); rep(i,0,n) cin>>a[i];
#define sortall(a) sort(a.begin(),a.end())
#define printall(a) rep(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
// ------------ My Template End ------------ //

int main()
{
    fastaf;
    cases
    {
        ll n,T,a,b; cin>>n>>T>>a>>b;
        vector<pll> v(n);
        rep(i,0,n) cin>>v[i].second;
        rep(i,0,n) cin>>v[i].first;
        sortall(v);
        ll easy=0; ll hard=0;
        rep(i,0,n)
        {
            if(v[i].ss==0) easy++;
            else hard++;
        }

        ll points=n; ll s=T;
        ll t=easy*a + hard*b; ll e=0; ll h=0;
        if(t<=s) { cout<<points<<endl; continue;}
        for(ll i=n-1;i>=0;i--)
        {
            s=v[i].ff-1; points--;
            if(v[i].ss==0)  { t-=a; e++;}
            else {t-=b; h++;}
            if(t<=s) break;
        }
        //cout<<s<<" "<<t<<endl;
        t=s-t; ll p=0;
        if(t>=a)
        {
            ll q=t/a;
            if(q>e) q=e;
            p+=q;
            t-=q*a;
            q=t/b;
            p+=q;
        }
        //cout<<p<<endl;
        points+=p;
        cout<<points<<endl;
    }
}


// ------------ My Template Start ------------ //
#include<bits/stdc++.h>
using namespace std;
#define fastaf ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long int
#define ull unsigned long long
#define vll vector<ll>
#define it(a) a.begin(),a.end()
#define pb push_back
#define ub(a,x) upper_bound(a.begin(),a.end(),x)
#define lb(a,x) lower_bound(a.begin(),a.end(),x)
#define bs(a,x) binary_search(a.begin(),a.end(),x)
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second
#define tll tuple<ll,ll,ll>
#define mt make_tuple
#define INF LONG_LONG_MAX
#define MOD 1000000007
#define mod 998244353
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define cases ll t; cin>>t; while(t--)
#define array(a,n) ll n; cin>>n; ll a[n]; rep(i,0,n) cin>>a[i];
#define vector(a,n) ll n; cin>>n; vll a(n); rep(i,0,n) cin>>a[i];
#define sortall(a) sort(a.begin(),a.end())
#define printall(a) rep(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
// ------------ My Template End ------------ //

int main()
{
    fastaf;
    cases
    {
        ll n,T,a,b; cin>>n>>T>>a>>b;
        vector<pll> v(n);
        rep(i,0,n) cin>>v[i].second;
        rep(i,0,n) cin>>v[i].first;
        sortall(v);
        ll easy=0; ll hard=0;
        rep(i,0,n)
        {
            if(v[i].ss==0) easy++;
            else hard++;
        }

        ll points=n; ll s=T;
        ll t=easy*a + hard*b; ll e=0; ll h=0;
        if(t<=s) { cout<<points<<endl; continue;}
        for(ll i=n-1;i>=0;i--)
        {
            s=v[i].ff-1; points--;
            if(v[i].ss==0)  { t-=a; e++;}
            else {t-=b; h++;}
            if(t<=s) break;
        }
        //cout<<s<<" "<<t<<endl;
        t=s-t; ll p=0;
        ll q=t/a;
        if(q>e) q=e;
        t-=q*a;
        if(q>0) p+=q;
        q=t/b;
        if(q>0) p+=q;

        //cout<<p<<endl;
        points+=p;
        cout<<points<<endl;
    }
}


// ------------ My Template Start ------------ //
#include<bits/stdc++.h>
using namespace std;
#define fastaf ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long int
#define ull unsigned long long
#define vll vector<ll>
#define it(a) a.begin(),a.end()
#define pb push_back
#define ub(a,x) upper_bound(a.begin(),a.end(),x)
#define lb(a,x) lower_bound(a.begin(),a.end(),x)
#define bs(a,x) binary_search(a.begin(),a.end(),x)
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second
#define tll tuple<ll,ll,ll>
#define mt make_tuple
#define INF LONG_LONG_MAX
#define MOD 1000000007
#define mod 998244353
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define cases ll t; cin>>t; while(t--)
#define array(a,n) ll n; cin>>n; ll a[n]; rep(i,0,n) cin>>a[i];
#define vector(a,n) ll n; cin>>n; vll a(n); rep(i,0,n) cin>>a[i];
#define sortall(a) sort(a.begin(),a.end())
#define printall(a) rep(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
// ------------ My Template End ------------ //

int main()
{
    fastaf;
    cases
    {
        ll n,T,a,b; cin>>n>>T>>a>>b;
        vector<pll> v(n);
        rep(i,0,n) cin>>v[i].second;
        rep(i,0,n) cin>>v[i].first;
        sortall(v);
        ll easy=0; ll hard=0;
        rep(i,0,n)
        {
            if(v[i].ss==0) easy++;
            else hard++;
        }

        ll points=n; ll s=T;
        ll t=easy*a + hard*b;
        if(t<=s) { cout<<points<<endl; continue;}
        for(ll i=n-1;i>=0;i--)
        {
            s=v[i].ff-1; points--;
            if(v[i].ss==0)  t-=a;
            else t-=b;
            if(t<=s) break;
        }
        t=v[0].ff-1; ll p=0;
        if(t>=a)
        {
            ll q=t/a;
            if(q>easy) q=easy;
            p+=q;
            t-=q*a;
            q=t/b;
            p+=q;
        }
        if(p>points) points=p;
        cout<<points<<endl;
    }
}


// ------------ My Template Start ------------ //
#include<bits/stdc++.h>
using namespace std;
#define fastaf ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long int
#define ull unsigned long long
#define vll vector<ll>
#define it(a) a.begin(),a.end()
#define pb push_back
#define ub(a,x) upper_bound(a.begin(),a.end(),x)
#define lb(a,x) lower_bound(a.begin(),a.end(),x)
#define bs(a,x) binary_search(a.begin(),a.end(),x)
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second
#define tll tuple<ll,ll,ll>
#define mt make_tuple
#define INF LONG_LONG_MAX
#define MOD 1000000007
#define mod 998244353
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define cases ll t; cin>>t; while(t--)
#define array(a,n) ll n; cin>>n; ll a[n]; rep(i,0,n) cin>>a[i];
#define vector(a,n) ll n; cin>>n; vll a(n); rep(i,0,n) cin>>a[i];
#define sortall(a) sort(a.begin(),a.end())
#define printall(a) rep(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
// ------------ My Template End ------------ //

int main()
{
    fastaf;
    cases
    {
        ll n,T,a,b; cin>>n>>T>>a>>b;
        vector<pll> v(n);
        rep(i,0,n) cin>>v[i].second;
        rep(i,0,n) cin>>v[i].first;
        sortall(v); v.pb(mp(T+1,0));
        ll easy=0; ll hard=0;
        rep(i,0,n)
        {
            if(v[i].ss==0) easy++;
            else hard++;
        }

        ll points=0;
        ll e=0; ll h=0; ll p=0;
        rep(i,0,n+1)
        {
            ll s=v[i].ff-1;
            ll t=e*a + h*b;
            if(t>s)
            {
                if(v[i].ss==0) { e++; easy--; }
                else { h++; hard--;}
                continue;
            }
            p=e+h;
            ll d=s-t;
            if(d>=a)
            {
                ll q=d/a; if(q>easy) q=easy;
                d-=q*a; p+=q;
                q=d/b; if(q>hard) q=hard;
                p+=q;
            }
            if(p>points) points=p;
            //cout<<i<<" -> "<<p<<endl;

            if(v[i].ss==0) { e++; easy--; }
            else { h++; hard--;}
        }

        cout<<points<<endl;
    }
}


// ------------ My Template Start ------------ //
#include<bits/stdc++.h>
using namespace std;
#define fastaf ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long int
#define ull unsigned long long
#define vll vector<ll>
#define it(a) a.begin(),a.end()
#define pb push_back
#define ub(a,x) upper_bound(a.begin(),a.end(),x)
#define lb(a,x) lower_bound(a.begin(),a.end(),x)
#define bs(a,x) binary_search(a.begin(),a.end(),x)
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second
#define tll tuple<ll,ll,ll>
#define mt make_tuple
#define INF LONG_LONG_MAX
#define MOD 1000000007
#define mod 998244353
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define cases ll t; cin>>t; while(t--)
#define array(a,n) ll n; cin>>n; ll a[n]; rep(i,0,n) cin>>a[i];
#define vector(a,n) ll n; cin>>n; vll a(n); rep(i,0,n) cin>>a[i];
#define sortall(a) sort(a.begin(),a.end())
#define printall(a) rep(i,0,a.size()) cout<<a[i]<<" "; cout<<endl;
// ------------ My Template End ------------ //

int main()
{
    fastaf;
    cases
    {
        ll n,T,a,b; cin>>n>>T>>a>>b;
        vector<pll> v(n);
        rep(i,0,n) cin>>v[i].second;
        rep(i,0,n) cin>>v[i].first;
        sortall(v); v.pb(mp(T+1,0));
        ll easy=0; ll hard=0;
        rep(i,0,n)
        {
            if(v[i].ss==0) easy++;
            else hard++;
        }

        ll points=0;
        ll e=0; ll h=0; ll p=0;
        rep(i,0,n+1)
        {
            ll s=v[i].ff-1;
            ll t=e*a + h*b;
            if(t>s)
            {
                if(v[i].ss==0) { e++; easy--; }
                else { h++; hard--;}
                continue;
            }
            p=e+h;
            ll d=s-t;
            if(d>=a)
            {
                ll q=d/a; if(q>easy) q=easy;
                d-=q*a; p+=q;
                q=d/b; if(q>hard) q=hard;
                p+=q;
            }
            if(p>points) points=p;

            if(v[i].ss==0) { e++; easy--; }
            else { h++; hard--;}
        }

        cout<<points<<endl;
    }
}


#include<bits/stdc++.h>

using namespace std;

#define pii pair<int, long long>
#define pb push_back
#define fi first
#define se second
#define N 200005
#define ll long long

pii arr[N];
int num_a[N];
int num_b[N];

int main(){
    ios_base :: sync_with_stdio(false);
    int testcase;
    cin >> testcase;
    int n , t , a , b;
    while(testcase--){
        cin >> n >> t >> a >> b;
        for(int i = 0 ; i < n ; i++){
            cin >> arr[i].se;
            if(arr[i].se == 0)
                arr[i].se = a;
            else
                arr[i].se = b;
        }

        for(int i = 0 ; i < n ; i++){
            cin >> arr[i].fi;
            num_a[i] = num_b[i] = 0;
        }

        sort(arr , arr + n);

        for(int i = n - 1 ; i >= 0 ; i--){
            if(arr[i].se == a){
                num_a[i] = 1;
                if(i != n - 1)
                    num_a[i] += num_a[i + 1];
            }

            else{
                num_b[i] = 1;
                if(i != n - 1)
                    num_b[i] += num_b[i + 1];
            }
        }
        int sum = 0;
        int ans = 0;
        int num;
        int temp , x;
        for(int i = 0 ; i < n ; i++){
            sum += arr[i].se;

            if(sum > t)
                break;
            if(i != n - 1 && arr[i + 1].fi <= sum)
                continue;

            num = i + 1;
            if(i != n - 1){
                temp = arr[i + 1].fi - sum;
                x = temp / a;
                num += min(x , num_a[i + 1]);
                temp -= min(x , num_a[i + 1]) * a;
                x = temp / b;
                num += min(x , num_b[i + 1]);
            }

            ans = max(ans , num);
        }
        cout << ans << endl;
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define N 200005
#define ll long long
#define fi first
#define se second
#define pii pair<int , int>
#define pb push_back

pii arr[N];
int cnt_a[N] , cnt_b[N];
int sum[N];

int main()
{
    ios_base :: sync_with_stdio(false);
    int testcase;
    cin >> testcase;
    int n , T , a , b;
    int ans , temp;
    int rem;
    while(testcase--){
        cin >> n >> T >> a >> b;
        ans = 0;
        for(int i = 0 ; i < n ; i++)
            cin >> arr[i].se;

        for(int i = 0 ; i < n ; i++)
            cin >> arr[i].fi;

        sort(arr , arr + n);

        for(int i = 0 ; i <= n ; i++){
            cnt_a[i] = cnt_b[i] = 0;
            sum[i] = 0;
        }

        for(int i = n - 2 ; i >= 0 ; i--){
            if(arr[i + 1].se == 0)
                cnt_a[i] ++;
            else
                cnt_b[i] ++;

            cnt_a[i] += cnt_a[i + 1];
            cnt_b[i] += cnt_b[i + 1];
        }

        for(int i = 0 ; i < n ; i++){
            if(arr[i].se == 0)
                sum[i] = a;
            else
                sum[i] = b;
            if(i != 0)
                sum[i] += sum[i - 1];
        }

        arr[n].fi = sum[n - 1] + 1;

        for(int i = 0 ; i < n ; i++){

            if(sum[i] >= arr[i + 1].fi)
                continue;

            if(sum[i] > T)
                break;

            if(i != n - 1)
                rem = arr[i + 1].fi - sum[i] - 1;
            else{
                rem = T - sum[i];
            }

            temp = i + 1;
            temp += min(rem / a , cnt_a[i]);
            rem -= (min(rem / a , cnt_a[i]) * a);
            temp += min(rem / b , cnt_b[i]);
            ans = max(ans , temp);
        }

        temp = 0;
        rem = arr[0].fi - 1;
        temp += (min(rem / a , cnt_a[0]));
        rem -= min(rem / a , cnt_a[0]) * a;
        temp += min(rem / b , cnt_b[0]);
        ans = max(ans , temp);
        cout << ans << endl;
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define pii pair<int, long long>
#define pb push_back
#define fi first
#define se second
#define N 200005
#define ll long long

pii arr[N];
int num_a[N];
int num_b[N];

int main(){
    ios_base :: sync_with_stdio(false);
    int testcase;
    cin >> testcase;
    int n , t , a , b;
    while(testcase--){
        cin >> n >> t >> a >> b;
        for(int i = 0 ; i < n ; i++){
            cin >> arr[i].se;
            if(arr[i].se == 0)
                arr[i].se = a;
            else
                arr[i].se = b;
        }

        for(int i = 0 ; i < n ; i++){
            cin >> arr[i].fi;
            num_a[i] = num_b[i] = 0;
        }
        num_a[n] = num_b[n] = 0;

        sort(arr , arr + n);

        for(int i = n - 1 ; i >= 0 ; i--){
            if(arr[i].se == a){
                num_a[i] = num_a[i + 1] + 1;
                num_b[i] = num_b[i + 1];
            }

            else{
                num_b[i] = 1 + num_b[i + 1];
                num_a[i] = num_a[i + 1];
            }
        }
        int sum = 0;
        int ans = 0;
        int num;
        int temp , x;
        for(int i = 0 ; i < n ; i++){
            sum += arr[i].se;

            if(sum > t)
                break;
            if(i != n - 1 && arr[i + 1].fi <= sum)
                continue;

            num = i + 1;
            if(i != n - 1){
                temp = arr[i + 1].fi - sum;
                x = temp / a;
                num += min(x , num_a[i + 1]);
                temp -= min(x , num_a[i + 1]) * a;
                x = temp / b;
                num += min(x , num_b[i + 1]);
            }

            ans = max(ans , num);
        }

        num = 0;
        temp = arr[0].fi;
        x = temp / a;
        num += min(x , num_a[1]);
        temp -= min(x , num_a[1]);
        x = temp / b;
        num += min(x , num_b[1]);
        ans = max(ans , num);
        cout << ans << endl;
    }
    return 0;
}