#include <bits/stdc++.h>

using ll = long long;
using namespace std;
const int INFint = 2e9+1;
const ll INFll = 2e18+1;
ll MOD=1e9+7;


int H,W,T;
string s[10];

int main(){
  int N,M;
  cin>>N>>M;
  vector<int> A(M);
  for(int i(0);i<M;i++){
    cin>>A[i];
  }
  sort(A.rbegin(),A.rend());
  int num[10] = {0,2,5,5,4,5,6,3,7,6};
  map<int,int> ma;
  set<int> honsuu;
  for(int i(0);i<M;i++){
    ma[num[A[i]]] = max(ma[num[A[i]]],A[i]);
    honsuu.insert(num[A[i]]);
  }
  int dp[10001] = {0}; //iを作るのに必要な最大個数
  for(auto m:honsuu){
    dp[m] = 1;
  }
  for(int i(0);i<=N;i++){
    for(auto m:honsuu){
      if(i-m >= 0 && dp[i-m] != 0){
        if(dp[i-m] + 1 >= dp[i]){
          dp[i] = dp[i-m] + 1;
        }
      }
    }
  }

  vector<int> ans;
  int now = N;
  while(dp[now] != 1){
    for(int i(0);i<M;i++){
      if(dp[now] - dp[now-num[A[i]]] == 1){
        ans.push_back(A[i]);
        now = now - num[A[i]];
        break;
      } 
    }
  }
  ans.push_back(ma[now]);

  sort(ans.rbegin(),ans.rend());
  for(int i(0);i<int(ans.size());i++){
    cout << ans[i];
  }
  cout << endl;
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> iint;
typedef pair<ll,ll> llll;
#define ALL(x) (x).begin(),(x).end()
const ll zero = 0;
const ll INF = 3000000000000000000; //10^18
const int inINF = 1000000000; //10^9
const ll MOD = 1000000007; //10^9+7
const ll MOD2 = 998244353;

int main(){
    int N, T;
    cin >> N >> T;
    vector<iint> A(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i].first >> A[i].second;
    }
    sort(ALL(A));

    vector<vector<int>> dp(N+1, vector<int>(T));
    int ans = 0;
    for (int i = 0; i < N+1; i++) {
        dp[i][0] = 0;
    }
    for (int i = 0; i < T; i++) {
        dp[0][i] = 0;
    }
    for (int n = 1; n < N+1; n++) {
        for (int t = 1; t < T; t++) {
            if(t - A[n-1].first >= 0){
                dp[n][t] = max(dp[n-1][t], dp[n-1][t-A[n-1].first] + A[n-1].second);
            }
            else{
                dp[n][t] = dp[n-1][t];
            }
        }
        for (int t = T; t < T+A[n-1].first; t++) {
            if(t - A[n-1].first >= 0){
                ans = max(ans, dp[n-1][t-A[n-1].first] + A[n-1].second);
            }
        }
    }

    printf("%d\n", ans);

}