Problem:


Score : 600 points

Problem Statement

The squirrel Chokudai has N acorns.
One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.

His plan is as follows:

Get out of the nest with N acorns in his hands.

Go to Exchange A and do some trades.

Go to Exchange B and do some trades.

Go to Exchange A and do some trades.

Go back to the nest.

In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:

Lose g_{X} acorns and gain 1 gram of gold.

Gain g_{X} acorns and lose 1 gram of gold.

Lose s_{X} acorns and gain 1 gram of silver.

Gain s_{X} acorns and lose 1 gram of silver.

Lose b_{X} acorns and gain 1 gram of bronze.

Gain b_{X} acorns and lose 1 gram of bronze.

Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.

What is the maximum number of acorns that he can bring to the nest?
Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.

Constraints

1 \leq N \leq 5000

1 \leq g_{X} \leq 5000

1 \leq s_{X} \leq 5000

1 \leq b_{X} \leq 5000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
g_A s_A b_A
g_B s_B b_B

Output

Print the maximum number of acorns that Chokudai can bring to the nest.

Sample Input 1

23
1 1 1
2 1 1

Sample Output 1

46

He can bring 46 acorns to the nest, as follows:

In Exchange A, trade 23 acorns for 23 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,0 }

In Exchange B, trade 23 grams of gold for 46 acorns. {acorns, gold, silver, bronze}={ 46,0,0,0 }

In Exchange A, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,0 }

He cannot have 47 or more acorns, so the answer is 46.



Sample input:
23
1 1 1
2 1 1


Sample output:
46

Submission status: Time Limit Exceeded

Solution code:
###############################################################################

import sys
from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict
import math


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def mod_inv(x):
    # available only when mod is prime
    global mod
    return pow(x, mod - 2, mod)


def gcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    ret = math.factorial(x)
    ret = ret // (math.factorial(x - y) * math.factorial(y))

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)


###############################################################################


wvalue = []
cache = {}


def f(n, wvaluelen):
    global cache, wvalue
    if (n, wvaluelen) in cache:
        return cache[(n, wvaluelen)]
    if wvaluelen == 0:
        return 0
    if wvaluelen == 1:
        w, value = wvalue[0]
        ret = value * (n // w)
        cache[(n, wvaluelen)] = ret
        return ret

    ret = -1
    w, value = wvalue[wvaluelen-1]
    for i in range(n // w + 1):
        ret = max(ret, i * value + f(n - i * w, wvaluelen - 1))

    cache[(n, wvaluelen)] = ret
    return ret


def main():
    global cache, wvalue
    sys.setrecursionlimit(10000)

    n = intin()
    gsb_a = intina()
    gsb_b = intina()

    ga = gsb_a[0]
    sa = gsb_a[1]
    ba = gsb_a[2]

    gb = gsb_b[0]
    sb = gsb_b[1]
    bb = gsb_b[2]

    # a: buy
    if gb - ga > 0:
        wvalue.append((ga, gb - ga))
    if sb - sa > 0:
        wvalue.append((sa, sb - sa))
    if bb - ba > 0:
        wvalue.append((ba, bb - ba))

    value = f(n, len(wvalue))
    cache = {}
    wvalue = []

    # b: sell
    n += value

    # b: buy
    if ga - gb > 0:
        wvalue.append((gb, ga - gb))
    if sa - sb > 0:
        wvalue.append((sb, sa - sb))
    if ba - bb > 0:
        wvalue.append((bb, ba - bb))

    value = f(n, len(wvalue))
    cache = {}
    wvalue = []

    # a: sell
    n += value

    print(n)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# coding: utf-8

def ri():
    return int(input())

def rl():
    return list(input().split())

def rli():
    return list(map(int, input().split()))

def main():
    n = ri()
    la = rli()
    lb = rli()

    dp = [i for i in range(n+1)]
    for i in range(len(dp)):
        for j in range(3):
            if la[j] <= i:
                dp[i] = max(dp[i], dp[i-la[j]]+lb[j])
    m = dp[n]

    dp = [i for i in range(m+1)]
    for i in range(len(dp)):
        for j in range(3):
            if lb[j] <= i:
                dp[i] = max(dp[i], dp[i-lb[j]]+la[j])
    print(dp[m])



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
gsbA = list(map(int,input().split()))
gsbB = list(map(int,input().split()))
ans = N
gRange = range(0,N+1,gsbA[0])
if gsbA[0]>=gsbB[0]:
    gRange = [0]
sRange = range(0,N+1,gsbA[1])
if gsbA[1]>=gsbB[1]:
    sRange = [0]

for g in gRange:
    for s in sRange:
        b = (N-g-s)//gsbA[2]*gsbA[2]
        if b<0:break
        ans =max(ans,N+sum(max(0,gsbB[i]-gsbA[i])*[g,s,b][i]//gsbA[i] for i in range(3)))
M = ans

gRange = range(0,M+1,gsbB[0])
if gsbA[0]<=gsbB[0]:
    gRange = [0]
sRange = range(0,M+1,gsbB[1])
if gsbA[1]<=gsbB[1]:
    sRange = [0]

for g in gRange:
    for s in sRange:
        b = (M-g-s)//gsbB[2]*gsbB[2]
        if b<0:break
        ans =max(ans,M+sum(max(0,gsbA[i]-gsbB[i])*[g,s,b][i]//gsbB[i] for i in range(3)))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
gsbA = list(map(int,input().split()))
gsbB = list(map(int,input().split()))
ans = N
gRange = range(0,N+1,gsbA[0])
if gsbA[0]>gsbB[0]:
    gRange = [0]
sRange = range(0,N+1,gsbA[1])
if gsbA[1]>gsbB[1]:
    sRange = [0]

for g in gRange:
    for s in sRange:
        b = (N-g-s)//gsbA[2]*gsbA[2]
        if b<0:break
        ans =max(ans,N+sum(max(0,gsbB[i]-gsbA[i])*[g,s,b][i]//gsbA[i] for i in range(3)))
M = ans

gRange = range(0,M+1,gsbB[0])
if gsbA[0]<gsbB[0]:
    gRange = [0]
sRange = range(0,M+1,gsbB[1])
if gsbA[1]<gsbB[1]:
    sRange = [0]

for g in gRange:
    for s in sRange:
        b = (M-g-s)//gsbB[2]*gsbB[2]
        if b<0:break
        ans =max(ans,M+sum(max(0,gsbA[i]-gsbB[i])*[g,s,b][i]//gsbB[i] for i in range(3)))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
if sys.version[0] == '2':
    range, input = xrange, raw_input
N = int(input())

A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

AB = [(a, b) for a, b in zip(A, B) if a < b]
dp = [[N] * (N + 1) for _ in range(len(AB)+1)]
for i, (a, b) in enumerate(AB):
    for w in range(N+1):
        if w >= a:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-a] + b-a)
        else:
            dp[i+1][w] = dp[i][w]

M = max(dp[-1])

BA = [(a, b) for a, b in zip(A, B) if a > b]
dp = [[M] * (M + 1) for _ in range(len(BA)+1)]
for i, (a, b) in enumerate(BA):
    for w in range(M+1):
        if w >= b:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-b] + a-b)
        else:
            dp[i+1][w] = dp[i][w]
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

AB = [(a, b) for a, b in zip(A, B) if a < b]
dp = [[N] * (N + 1) for _ in range(len(AB)+1)]
for i, (a, b) in enumerate(AB):
    for w in range(N+1):
        if w >= a:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-a] + b-a)
        else:
            dp[i+1][w] = dp[i][w]

M = max(dp[-1])

BA = [(a, b) for a, b in zip(A, B) if a > b]
dp = [[M] * (M + 1) for _ in range(len(BA)+1)]
for i, (a, b) in enumerate(BA):
    for w in range(M+1):
        if w >= b:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-b] + a-b)
        else:
            dp[i+1][w] = dp[i][w]
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    w1 = list(map(int,input().split()))
    w2 = list(map(int,input().split()))
    v1 = [0,0,0]
    for i in range(3):
        v1[i] = w2[i] - w1[i]
    dp1 = [0] * (n+1)
    for i in range(n):
        p = 0
        q = 0
        r = 0
        if i+1 - w1[0] >= 0:
            p = dp1[i+1 - w1[0]] + v1[0]
        if i+1 - w1[1] >= 0:
            q = dp1[i+1 - w1[1]] + v1[1]
        if i+1 - w1[2] >= 0:
            r = dp1[i+1 - w1[2]] + v1[2]
        dp1[i+1] = max(p,q,r,dp1[i])
    m = dp1[-1] + n

    v2 = [0,0,0]
    for i in range(3):
        v2[i] = w1[i] - w2[i]
    dp2 = [0] * (m+1)
    for i in range(m):
        p = 0
        q = 0
        r = 0
        if i+1 - w2[0] >= 0:
            p = dp2[i+1 - w2[0]] + v2[0]
        if i+1 - w2[1] >= 0:
            q = dp2[i+1 - w2[1]] + v2[1]
        if i+1 - w2[2] >= 0:
            r = dp2[i+1 - w2[2]] + v2[2]
        dp2[i+1] = max(p,q,r,dp2[i])
    print(m + dp2[-1])
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False
def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
b = inl()

t = [ [-1] * (n+1) for i in range(3) ]
for i in range(3):
    t[i][0] = 0

mx = 0
for i in range(3):
    aa = a[i]
    x = b[i]-a[i]
    for j in range(1,n+1):
        tij = -1
        if i>0:
            tij = t[i-1][j]
        if j>=aa and t[i][j-aa] != -1:
            tij = max(tij, t[i][j-aa]+x)
        t[i][j] = tij
        mx = max(mx, tij)

n += mx

t = [ [-1] * (n+1) for i in range(3) ]
for i in range(3):
    t[i][0] = 0

mx = 0
for i in range(3):
    bb = b[i]
    x = a[i]-b[i]
    for j in range(1,n+1):
        tij = -1
        if i>0:
            tij = t[i-1][j]
        if j>=bb and t[i][j-bb] != -1:
            tij = max(tij, t[i][j-bb]+x)
        t[i][j] = tij
        mx = max(mx, tij)

print(n+mx)

Submission status: Time Limit Exceeded

Solution code:
import sys,heapq
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False
def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
b = inl()

t = [ [-1] * (n+1) for i in range(3) ]
for i in range(3):
    t[i][0] = 0

mx = 0
for i in range(3):
    aa = a[i]
    x = b[i]-a[i]
    for j in range(n+1):
        if i>0:
            t[i][j] = t[i-1][j]
        if j>=aa and t[i][j-aa] != -1:
            t[i][j] = max(t[i][j], t[i][j-aa]+x)
        mx = max(mx, t[i][j])

n += mx
if DBG:
    for i in range(3):
        print(t[i])
ddprint(n)

t = [ [-1] * (n+1) for i in range(3) ]
for i in range(3):
    t[i][0] = 0

mx = 0
for i in range(3):
    bb = b[i]
    x = a[i]-b[i]
    for j in range(n+1):
        if i>0:
            t[i][j] = t[i-1][j]
        if j>=bb and t[i][j-bb] != -1:
            t[i][j] = max(t[i][j], t[i][j-bb]+x)
        mx = max(mx, t[i][j])

if DBG:
    for i in range(3):
        print(t[i])

print(n+mx)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n,k = LI()
    print(n%k)
    return

#B
def B():
    n = I()
    po = LIR(n)
    if n == 1:
        print(1)
        quit()
    ans = float("inf")
    for i in range(n):
        for j in range(n):
            if i == j:continue
            x,y = po[i]
            s,t = po[j]
            p,q = s-x,t-y
            m = n
            for k in range(n):
                for l in range(n):
                    if (po[k][0]-po[l][0],po[k][1]-po[l][1]) == (p,q):m -= 1
            if m < ans:
                ans = m
    print(ans)
    return

#C
def C():
    n = I()
    a = LI()
    a.sort()
    if a[0] >= 0:
        print(sum(a)-2*a[0])
        for i in range(1,n-1):
            print(a[0],a[i])
            a[0] -= a[i]
        print(a[n-1],a[0])
    else:
        if a[-1] < 0:
            print(2*a[-1]-sum(a))
            for i in range(n-1):
                print(a[-1],a[i])
                a[-1] -= a[i]
        else:
            m = bisect.bisect_left(a,0)
            p = n-m
            ans = -sum(a[:m])+sum(a[m:])
            print(ans)
            if p > m:
                l = a[-1]
                a = a[:-1]
                a = a[::-1]
                p -= 1
                p,m = m,p
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
                print(l,k)
            else:
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
    return

#D
def D():
    n = I()
    a = LI()
    b = LI()
    dp = [0 for i in range(n+1)]
    for w in range(n+1):
        dp[w] = w
        x0 = dp[w-a[0]]+b[0] if w-a[0] >= 0 else w
        x1 = dp[w-a[1]]+b[1] if w-a[1] >= 0 else w
        x2 = dp[w-a[2]]+b[2] if w-a[2] >= 0 else w
        dp[w] = max(dp[w],x0,x1,x2)
    n = dp[n]
    dp = [0 for i in range(n+1)]
    for w in range(n+1):
        dp[w] = w
        x0 = dp[w-b[0]]+a[0] if w-b[0] >= 0 else w
        x1 = dp[w-b[1]]+a[1] if w-b[1] >= 0 else w
        x2 = dp[w-b[2]]+a[2] if w-b[2] >= 0 else w
        dp[w] = max(dp[w],x0,x1,x2)
    print(dp[n])
    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#G
def G():
    n = I()

    return

#H
def H():
    n = I()

    return

#I
def I_():
    n = I()

    return

#J
def J():
    n = I()

    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n,k = LI()
    print(n%k)
    return

#B
def B():
    n = I()
    po = LIR(n)
    if n == 1:
        print(1)
        quit()
    ans = float("inf")
    for i in range(n):
        for j in range(n):
            if i == j:continue
            x,y = po[i]
            s,t = po[j]
            p,q = s-x,t-y
            m = n
            for k in range(n):
                for l in range(n):
                    if (po[k][0]-po[l][0],po[k][1]-po[l][1]) == (p,q):m -= 1
            if m < ans:
                ans = m
    print(ans)
    return

#C
def C():
    n = I()
    a = LI()
    a.sort()
    if a[0] >= 0:
        print(sum(a)-2*a[0])
        for i in range(1,n-1):
            print(a[0],a[i])
            a[0] -= a[i]
        print(a[n-1],a[0])
    else:
        if a[-1] < 0:
            print(2*a[-1]-sum(a))
            for i in range(n-1):
                print(a[-1],a[i])
                a[-1] -= a[i]
        else:
            m = bisect.bisect_left(a,0)
            p = n-m
            ans = -sum(a[:m])+sum(a[m:])
            print(ans)
            if p > m:
                l = a[-1]
                a = a[:-1]
                a = a[::-1]
                p -= 1
                p,m = m,p
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
                print(l,k)
            else:
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
    return

#D
def D():
    n = I()
    a = LI()
    b = LI()
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        x0 = dp[w-a[0]]+b[0] if w-a[0] >= 0 else w
        x1 = dp[w-a[1]]+b[1] if w-a[1] >= 0 else w
        x2 = dp[w-a[2]]+b[2] if w-a[2] >= 0 else w
        dp[w] = max(dp[w],x0,x1,x2)
    n = dp[n]
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        x0 = dp[w-b[0]]+a[0] if w-b[0] >= 0 else w
        x1 = dp[w-b[1]]+a[1] if w-b[1] >= 0 else w
        x2 = dp[w-b[2]]+a[2] if w-b[2] >= 0 else w
        dp[w] = max(dp[w],x0,x1,x2)
    print(dp[n])
    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#G
def G():
    n = I()

    return

#H
def H():
    n = I()

    return

#I
def I_():
    n = I()

    return

#J
def J():
    n = I()

    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

dp = [[N] * (N + 1) for _ in range(4)]
for i in range(3):
    for w in range(N+1):
        if w >= A[i]:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-A[i]] + B[i]-A[i])
        else:
            dp[i+1][w] = dp[i][w]

M = max(dp[-1])

dp = [[M] * (M + 1) for _ in range(4)]
for i in range(3):
    for w in range(M+1):
        if w >= B[i]:
            dp[i+1][w] = max(dp[i][w], dp[i+1][w-B[i]] + A[i]-B[i])
        else:
            dp[i+1][w] = dp[i][w]
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def YesNo(x): return 'Yes' if x else 'No'
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()

def nap(n, gsbA, gsbB):
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        tmp = dp[i - 1] + 1
        for mA, mB in zip(gsbA, gsbB):
            if i - mA >= 0:
                tmp = max(tmp, mB + dp[i - mA])
        dp[i] = tmp
    return dp[n]

def main():
    N = II()
    gsbA = LI()
    gsbB = LI()
    ans = nap(N, gsbA, gsbB)
    ans = nap(ans, gsbB, gsbA)
    return ans

print(main())

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n,k = LI()
    print(n%k)
    return

#B
def B():
    n = I()
    po = LIR(n)
    if n == 1:
        print(1)
        quit()
    ans = float("inf")
    for i in range(n):
        for j in range(n):
            if i == j:continue
            x,y = po[i]
            s,t = po[j]
            p,q = s-x,t-y
            m = n
            for k in range(n):
                for l in range(n):
                    if (po[k][0]-po[l][0],po[k][1]-po[l][1]) == (p,q):m -= 1
            if m < ans:
                ans = m
    print(ans)
    return

#C
def C():
    n = I()
    a = LI()
    a.sort()
    if a[0] >= 0:
        print(sum(a)-2*a[0])
        for i in range(1,n-1):
            print(a[0],a[i])
            a[0] -= a[i]
        print(a[n-1],a[0])
    else:
        if a[-1] < 0:
            print(2*a[-1]-sum(a))
            for i in range(n-1):
                print(a[-1],a[i])
                a[-1] -= a[i]
        else:
            m = bisect.bisect_left(a,0)
            p = n-m
            ans = -sum(a[:m])+sum(a[m:])
            print(ans)
            if p > m:
                l = a[-1]
                a = a[:-1]
                a = a[::-1]
                p -= 1
                p,m = m,p
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
                print(l,k)
            else:
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
    return

#D
def D():
    n = I()
    a = LI()
    b = LI()
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        for i in range(3):
            if w-a[i] >= 0:
                x = dp[w-a[i]]+b[i]
                if x > dp[w]:
                    dp[w] = x
    n = dp[n]
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        for i in range(3):
            if w-b[i] >= 0:
                x = dp[w-b[i]]+a[i]
                if x > dp[w]:
                    dp[w] = x
    print(dp[n])
    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#G
def G():
    n = I()

    return

#H
def H():
    n = I()

    return

#I
def I_():
    n = I()

    return

#J
def J():
    n = I()

    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
gA, sA, bA = map(int, input().split())
gB, sB, bB = map(int, input().split())

#[重さ,価値]を要素とする配列
lstAB_2 = [[gA, gB-gA], [sA, sB-sA], [bA, bB-bA]]
lstBA_2 = [[gB, gA-gB], [sB, sA-sB], [bB, bA-bB]]
lstAB = []
for i in range(3):
    if lstAB_2[i][1] > 0:
        lstAB += [lstAB_2[i]]  

lstBA = []
for i in range(3):
    if lstBA_2[i][1] > 0:
        lstBA += [lstBA_2[i]]

dp = [[0] * (N+1) for _ in range(len(lstAB)+1)]
for i in range(len(lstAB)):
    for j in range(N+1):
        if j < lstAB[i][0]:
            dp[i+1][j] = dp[i][j]
        else:
            dp[i+1][j] = max(dp[i][j], dp[i+1][j-lstAB[i][0]]+lstAB[i][1])

N += dp[len(lstAB)][N]
# print (N)

dp2 = [[0] * (N+1) for _ in range(len(lstBA)+1)]
for i in range(len(lstBA)):
    for j in range(N+1):
        if j < lstBA[i][0]:
            dp2[i+1][j] = dp2[i][j]
        else:
            dp2[i+1][j] = max(dp2[i][j], dp2[i+1][j-lstBA[i][0]]+lstBA[i][1])
print (N + dp2[len(lstBA)][N])

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n,k = LI()
    print(n%k)
    return

#B
def B():
    n = I()
    po = LIR(n)
    if n == 1:
        print(1)
        quit()
    ans = float("inf")
    for i in range(n):
        for j in range(n):
            if i == j:continue
            x,y = po[i]
            s,t = po[j]
            p,q = s-x,t-y
            m = n
            for k in range(n):
                for l in range(n):
                    if (po[k][0]-po[l][0],po[k][1]-po[l][1]) == (p,q):m -= 1
            if m < ans:
                ans = m
    print(ans)
    return

#C
def C():
    n = I()
    a = LI()
    a.sort()
    if a[0] >= 0:
        print(sum(a)-2*a[0])
        for i in range(1,n-1):
            print(a[0],a[i])
            a[0] -= a[i]
        print(a[n-1],a[0])
    else:
        if a[-1] < 0:
            print(2*a[-1]-sum(a))
            for i in range(n-1):
                print(a[-1],a[i])
                a[-1] -= a[i]
        else:
            m = bisect.bisect_left(a,0)
            p = n-m
            ans = -sum(a[:m])+sum(a[m:])
            print(ans)
            if p > m:
                l = a[-1]
                a = a[:-1]
                a = a[::-1]
                p -= 1
                p,m = m,p
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
                print(l,k)
            else:
                k = a[m]-a[m-1]
                print(a[m],a[m-1])
                for i in range(p-1):
                    print(a[m-i-2],k)
                    k = a[m-i-2]-k
                    print(a[m+i+1],k)
                    k = a[m+i+1]-k
                for i in range(m-p):
                    print(k,a[i])
                    k -= a[i]
    return

#D
def D():
    n = I()
    a = LI()
    b = LI()
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        for i in range(3):
            if w-a[i] >= 0:
                if dp[w-a[i]]+b[i] > dp[w]:
                    dp[w] = dp[w-a[i]]+b[i]
    n = dp[n]
    dp = defaultdict(int)
    for w in range(n+1):
        dp[w] = w
        for i in range(3):
            if w-b[i] >= 0:
                if dp[w-b[i]]+a[i] > dp[w]:
                    dp[w] = dp[w-b[i]]+a[i]
    print(dp[n])
    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#G
def G():
    n = I()

    return

#H
def H():
    n = I()

    return

#I
def I_():
    n = I()

    return

#J
def J():
    n = I()

    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Time Limit Exceeded

Solution code:
def getlist():
	return list(map(int, input().split()))

N = int(input())
A = getlist()
B = getlist()


L = [0 for i in range(N + 1)]
l1 = []
l2 = []
for i in range(3):
	if B[i] - A[i] > 0:
		l1.append([A[i], B[i]])
	elif B[i] - A[i] < 0:
		l2.append([B[i], A[i]])

c = 0
n = 0
a = len(l1)
for i in range(N + 1):
	for j in range(a):
		x = l1[j][0]
		if i + x <= N:
			if L[i] + l1[j][1] > L[i + x]:
				L[i + x] = L[i] + l1[j][1]
		if L[i] > c:
			c = L[i]
			n = i

N += c - n
c = 0
n = 0
b = len(l2)
L = [0 for i in range(N + 1)]
for i in range(N + 1):
	for j in range(b):
		x = l2[j][0]
		y = L[i]
		if i + x <= N:
			L[i + x] = max(L[i + x], y + l2[j][1])
		if y > c:
			c = y
			n = i

N += c - n
print(N)