import sys read=sys.stdin.buffer.read readline=sys.stdin.buffer.readline readlines=sys.stdin.buffer.readlines t=int(readline()) n=int(readline()) c=list(map(int, readline().split())) v=list(map(int, readline().split())) dp=[0]*(t+1) for x, y in zip(c, v): while y: for i in range(t-x, -1, -1): dp[i+x]=max(dp[i+x], dp[i]+y) y>>=1 print(dp[t])