f = lambda x:x[0] def omit(lst): lst.sort(key=f) q = [] for a,b in lst: while q and q[-1][1] <= b: q.pop() if not q or q[-1][0] < a: q.append((a,b)) return q def dfs(s,t): dp = [[] for _ in range(t+3)] dp[s] = [(0,0)] for i in range(s,t): q = omit(dp[i]) dp[i+1] += [(m+a[i],v) for m,v in q] dp[i+2] += [(m-c[i+1],v+b[i+1]) for m,v in q] return omit(dp[t]) def solve(x,y): ans = idx = 0 L = len(x) for m,v in y[::-1]: while idx < L and x[idx][0] + m < 0: idx += 1 if idx < L: ans = max(ans,x[idx][1]+v) return ans w,*m = map(int,open(0).read().split()) a,b,c = m[::3]+[0],m[1::3]+[0],m[2::3]+[0] ans = 0 for W in [w//2,w//2+1]: x = dfs(0,W) y = dfs(W,w) ans = max(ans,solve(x,y)) print(ans)