#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0, i##_len = (n); i < i##_len; ++i)
#define rep2(i, x, n) for(int i = x, i##_len = (n); i < i##_len; ++i)
#define all(n) begin(n), end(n)
using ll = long long;
using P = pair<int, int>;
using vi = vector<int>;
using vl = vector<ll>;
using vs = vector<string>;
using vc = vector<char>;
using vb = vector<bool>;
using vd = vector<double>;
vi dir = {-1, 0, 1, 0, -1, -1, 1, 1, -1};

int main() {
  int n, m;
  cin >> n >> m;
  vi a(m);
  rep(i, m) cin >> a[i];
  vi b = {0, 2, 5, 5, 4, 5, 6, 3, 7, 6};
  vi dp(n + 1, -1);
  dp[0] = 0;
  rep(j, n) rep(i, m) {
    if(dp[j] == -1) continue;
    int nj = j + b[a[i]];
    if(nj <= n) dp[nj] = max(dp[nj], dp[j] + 1);
  }
  int j = n;
  string ans = "";
  while(j) {
    int num = 0;
    rep(i, m) {
      int nj = j - b[a[i]];
      if(nj >= 0 && dp[nj] == dp[j] - 1) num = max(num, a[i]);
    }
    ans.push_back((char)(num + '0'));
    j -= b[num];
  }
  cout << ans << endl;
}
#include<bits/stdc++.h>
using namespace std;
int read() {
    char cc = getchar(); int cn = 0, flus = 1;
    while(cc < '0' || cc > '9') {  if( cc == '-' ) flus = -flus;  cc = getchar();  }
    while(cc >= '0' && cc <= '9')  cn = cn * 10 + cc - '0', cc = getchar();
    return cn * flus;
}
const int N = 1000 + 5 ; 
#define rep( i, s, t ) for( register int i = s; i <= t; ++ i )
int n, m, book[N], w[N][N], vis[N], can[N];   
bool check( int x ) {
    memset( book, 0, sizeof(book) ), memset( can, 0, sizeof(can) ) ;
    int flag ; rep( i, 1, n ) vis[i] = 1, ++ book[w[i][vis[i]]] ; 
    rep( i, 1, m ) {
        flag = 1 ; 
        rep( j, 1, n ) {
            int u = w[j][vis[j]] ; 
            if( book[u] > x ) {
                can[u] = 1; flag = 0 ; 
                while( vis[j] <= n && can[w[j][vis[j]]] ) ++ vis[j] ; 
                if( vis[j] > n ) return 0; 
                ++ book[w[j][vis[j]]] ; 
            }
        }
        if( flag ) return 1; 
    }
    return 0 ; 
}
signed main()
{
    n = read(), m = read() ; 
    rep( i, 1, n ) rep( j, 1, m ) w[i][j] = read() ; 
    int l = 1, r = n, ans = 0, mid ; 
    while( l <= r ) {
        mid = ( l + r ) >> 1 ; 
        if( check(mid) ) ans = mid, r = mid - 1 ; 
        else l = mid + 1 ; 
    }
    printf("%d\n", ans ) ; 
    return 0;
}