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: Runtime Error

Solution code:
N = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())

dp = [0]*(N*2)

G = N//ga

for g in range(1, G+1):
    temp = g*ga
    dp[temp] = g*gb
    rest = N - g
    S = rest//sa
    for s in range(1, S+1):
        temp2 = temp+s*sa
        dp[temp2] = max(dp[temp2], dp[temp]+s*sb)
        rest = rest - s
        B = rest//ba
        for b in range(1, B+1):
            temp3 = temp2+b*ba
            dp[temp3] = max(dp[temp3], dp[temp2]+b*bb)

print(max(dp))

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print([A[0]/B[0],A[1]/B[1],A[2]/B[2],B[0]/A[0],B[1]/A[1],B[2]/A[2]])

l = set
max_item = N
l.add(N)
for i in [0,1,2]:
  if A[i] == B[i]:
    pass
  else:
    d = max(A[i],B[i])
    n = min(A[i],B[i])
    if d%n==0:
      l.add(N*d)
    else:  
      l = [x*A[1]　if x*d%n==0 for x in range(1,N+1) ]
      l.add(max(l))
      
print(max(l))

Submission status: Runtime Error

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n=I()
  g1,s1,b1=LI()
  g2,s2,b2=LI()

  # Aで終わらせる場合1
  ans1=n
  # Bで終わらせる場合
  if g2-g1>0 and g2-g1>=s2-s1 and g2-g1>=b2-b1:
    ans2=n%g1+(n//g1)*(g2-g1+1)
  elif s2-s1>0 and s2-s1>=g2-g1 and s2-s1>=b2-b1:
    ans2=n%s1+(n//s1)*(s2-s1+1)
  elif b2-b1>0 and b2-b1>=g2-g1 and b2-b1>=s2-s1:
    ans2=n%b1+(n//b1)*(b2-b1+1)
  # Aで終わらせる場合2

  return max(ans1,ans2)

print(main())

Submission status: Runtime Error

Solution code:
def gcd(a,b):
    if b>a:
        a,b=b,a
    while b:
        a,b=b, a%b
    return a

def f(a,b,N):
    l=[]
    for i in range(3):
        if a[i]<b[i]: l.append(i)

    if len(l)==0: return N
    if len(l)==1:
        l=l[0]
        return (N//a[l])*b[l]+N%a[l]
    elif len(l)==2:
        x,y=l[0],l[1]
        p,q=a[x],a[y]
        lcm=p*q//gcd(p,q)

        n1,n2=N-N%lcm,N%lcm
        ans1=max(n1*b[x]//p,n1*b[y]//q)
        i=0
        ans2=0
        while i*p<=n2:
            ans2=max(ans2,i*b[x]+((n2-i*p)//q)*b[y])
            i+=1
        return ans1+ans2
        
    else:
        p,q,r=a[0]
        lcm=a[0]*a[1]//gcd(a[0],a[1])
        lcm=lcm*a[2]//gcd(a[2],lcm)
        n1,n2=N-N%lcm,N%lcm
        ans1=max(n1*b[i]//a[i] for i in range(3))
        i=0
        ans2=0
        while i*a[0]<=n2:
            n3=n2-i*a[0]
            j=0
            while  j*a[1]<=n3:
                ans2=max(ans2,i*b[0]+j*b[1]+(n3-j*a[1])*b[2])
                j+=1
            i+=1
        return ans1+ans2

import sys
N=int(input())

a=list(map(int,input().split()))
b=list(map(int,input().split()))

N=f(a,b,N)
N=f(b,a,N)
print(int(N))

Submission status: Runtime Error

Solution code:
print "46"

Submission status: Runtime Error

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

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


L = [0 for i in range(N + 10)]
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
for i in range(N + 1):
	for j in range(len(l1)):
		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
L = [0 for i in range(N + 10)]
for i in range(N + 1):
	for j in range(len(l2)):
		x = l2[j][0]
		if i + x <= N:
			if L[i] + l2[j][1] > L[i + x]:
				L[i + x] = L[i] + l2[j][1]
		if L[i] > c:
			c = L[i]
			n = i

N += c - n
print(N)

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
dp=[[0]*(n+1) for i in range(7)]
for i in range(n+1):
    dp[0][i]=i
for i in range(n):
    dp[1][i+1]=max(dp[0][i+1],dp[1][(i+1)%a[0]]+(i+1)//a[0]*b[0])
for i in range(n):
    dp[2][i+1]=max(dp[1][i+1],dp[2][(i+1)%a[1]]+(i+1)//a[1]*b[1])
for i in range(n):
    dp[3][i+1]=max(dp[2][i+1],dp[3][(i+1)%a[2]]+(i+1)//a[2]*b[2])

for i in range(n):
    dp[4][i+1]=max(dp[3][i+1],dp[4][dp[3][i+1]%b[0]]+dp[3][i+1]//b[0]*a[0])
for i in range(n):
    dp[5][i+1]=max(dp[4][i+1],dp[5][dp[3][i+1]%b[1]]+dp[3][i+1]//b[1]*a[1])
for i in range(n):
    dp[6][i+1]=max(dp[5][i+1],dp[6][dp[3][i+1]%b[2]]+dp[3][i+1]//b[2]*a[2])
print(dp[-1][-1])

Submission status: Runtime Error

Solution code:
import sys
#input = sys.stdin.readline
from sys import setrecursionlimit
setrecursionlimit(10**9)

def inpl(): return list(map(int, input().split()))
N = int(input())
GA = inpl()
GB = inpl()

typ = [GA[i] <= GB[i] for i in range(3)]

if sum(typ) == 3:
    ans = 0
    for g in range(N//GA[0] + 1):
        D = N - GA[0]*g
        for s in range(D//GA[1] + 1):
            b, D2 = divmod(D - GA[1]*s, GA[2])
            ans = max(ans, D2 + g*GB[0] + s*GB[1] + b*GB[2])

elif sum(typ) == 2:
    ans = 0
    x, y = [i for i in range(3) if typ[i]]
    z = [i for i in range(3) if not typ[i]][0]
    for a in range(N//GA[x] + 1):
        b, D = divmod(N - GA[x]*a, GA[y])
        c, D2 = divmod(D + GB[x]*a + GB[y]*b, GB[z])
        ans = max(ans, D2 + c*GA[z])

elif sum(typ) == 1:
    ans = 0
    raise
    x, y = [i for i in range(3) if not typ[i]]
    z = [i for i in range(3) if typ[i]][0]
    c, D = divmod(N, GA[z])
    D += GB[z]*c

    for a in range(D//GB[x] + 1):
        b, D2 = divmod(D-GB[x]*a, GB[y])
        ans = max(ans, D2 + GA[x]*a + GB[y]*b)

else:
    ans = 0
    for g in range(N//GB[0] + 1):
        D = N - GB[0]*g
        for s in range(D//GB[1] + 1):
            b, D2 = divmod(D - GB[1]*s, GB[2])
            ans = max(ans, D2 + g*GA[0] + s*GA[1] + b*GA[2])

print(ans)

Submission status: Runtime Error

Solution code:
import itertools
N=int(input())
ga,sa,ba=[int(i) for i in input().split(" ")]
gb,sb,bb=[int(i) for i in input().split(" ")]
cmd=["getgold","paygold","getsilver","paysilver","getbronze","paybronze","fin"]
cmds=[]
from tqdm import tqdm
for g in ("getgold","paygold","fin"):
    for s in ("getsilver","paysilver","fin"):
        for b in ("getbronze","paybronze","fin"):
            cmds.append((g,s,b))
            cmds.append((g,b,s))
            cmds.append((s,g,b))
            cmds.append((s,b,g))
            cmds.append((b,g,s))
            cmds.append((b,s,g))



def award(donguri,gold,silver,bronze,cmd,X):
    if X=="A":
        g,s,b=ga,sa,ba
    else:
        g,s,b=gb,sb,bb
    for c in cmd:
        if c=="fin":
            return donguri,gold,silver,bronze
        elif c=="getgold":
            gold+=donguri//g
            donguri=donguri%g
        elif c=="paygold":
            donguri+=gold*g
            gold=0
        elif c=="getsilver":
            silver+=donguri//s
            donguri=donguri%s
        elif c=="paysilver":
            donguri+=silver*s
            silver=0
        elif c=="getbronze":
            bronze+=donguri//b
            donguri=donguri%b
        elif c=="paybronze":
            donguri+=bronze*b
            bronze=0
    return donguri,gold,silver,bronze


retval=0
for cmd1 in cmds:
    for cmd2 in cmds:
            donguri=N
            gold=0
            silver=0
            bronze=0
            donguri,gold,silver,bronze=award(donguri,gold,silver,bronze,cmd1,"A")
            donguri,gold,silver,bronze=award(donguri,gold,silver,bronze,cmd2,"B")
            donguri+=ga*gold+sa*silver+ba*bronze
            retval=max(retval,donguri)

print(retval)

Submission status: Runtime Error

Solution code:
import sys
#input = sys.stdin.readline
from sys import setrecursionlimit
setrecursionlimit(10**9)

def inpl(): return list(map(int, input().split()))
N = int(input())
GA = inpl()
GB = inpl()

typ = [GA[i] <= GB[i] for i in range(3)]

if sum(typ) == 3:
    ans = 0
    for g in range(N//GA[0] + 1):
        D = N - GA[0]*g
        for s in range(D//GA[1] + 1):
            b, D2 = divmod(D - GA[1]*s, GA[2])
            ans = max(ans, D2 + g*GB[0] + s*GB[1] + b*GB[2])

elif sum(typ) == 2:
    ans = 0
    x, y = [i for i in range(3) if typ[i]]
    z = [i for i in range(3) if not typ[i]][0]
    for a in range(N//GA[x] + 1):
        b, D = divmod(N - GA[x]*a, GA[y])
        c, D2 = divmod(D + GB[x]*a + GB[y]*b, GB[z])
        ans = max(ans, D2 + c*GA[z])
        raise

elif sum(typ) == 1:
    ans = 0
    x, y = [i for i in range(3) if not typ[i]]
    z = [i for i in range(3) if typ[i]][0]
    c, D = divmod(N, GA[z])
    D += GB[z]*c

    for a in range(D//GB[x] + 1):
        b, D2 = divmod(D-GB[x]*a, GB[y])
        ans = max(ans, D2 + GA[x]*a + GB[y]*b)

else:
    ans = 0
    for g in range(N//GB[0] + 1):
        D = N - GB[0]*g
        for s in range(D//GB[1] + 1):
            b, D2 = divmod(D - GB[1]*s, GB[2])
            ans = max(ans, D2 + g*GA[0] + s*GA[1] + b*GA[2])

print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
a1, a2, a3 = map(int, input().split())
b1, b2, b3 = map(int, input().split())
A = [a1, a2, a3]
B = [b1, b2, b3]
if (a1<=b1 and a2<=b2 and a3<=b3) or (a1>=b1 and a2>=b2 and a3>=b3):
    if a1>b1 or a2>b2 or a3>b3:
        A, B = B, A
    dp = [[-float("inf")]*(N+1+5050) for _ in range(4)]
    dp[0][0] = 0
    for i in range(3):
        ai = A[i]
        bi = B[i]
        for j in range(N+1):

            dp[i+1][j] = max(dp[i][j], dp[i+1][j-ai]+bi)
    print(max(dp[3]))
    assert False
    #print(dp[3][:30])
else:
    C, D = [], []
    for a, b in zip(A, B):
        if a <= b:
            C.append([a,b])
        else:
            D.append([b, a])

    if len(C)==1:
        a, b = C[0]
        q, n = divmod(N, a)
        N_ = q*b + n
    else:
        N_ = N
        (a1, b1), (a2, b2) = C
        for i in range(N + 1):
            j = N - i
            q1, n1 = divmod(i, a1)
            q2, n2 = divmod(j, a2)
            N_ = max(N_, q1 * b1 + q2 * b2 + n1 + n2)

    if len(D)==1:
        a, b = D[0]
        q, n = divmod(N_, a)
        print(q*b + n)
        #print("a")
    else:
        ans = N_
        (a1, b1), (a2, b2) = D
        for i in range(N_+1):
            j = N_ - i
            q1, n1 = divmod(i, a1)
            q2, n2 = divmod(j, a2)
            ans = max(ans, q1*b1+q2*b2+n1+n2)
        print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
a1, a2, a3 = map(int, input().split())
b1, b2, b3 = map(int, input().split())
A = [a1, a2, a3]
B = [b1, b2, b3]
if (a1<=b1 and a2<=b2 and a3<=b3) or (a1>=b1 and a2>=b2 and a3>=b3):
    if a1>b1 or a2>b2 or a3>b3:
        A, B = B, A
    dp = [[-float("inf")]*(N+1+5050) for _ in range(4)]
    dp[0][0] = 0
    for i in range(3):
        ai = A[i]
        bi = B[i]
        for j in range(N+1):

            dp[i+1][j] = max(dp[i][j], dp[i+1][j-ai]+bi)
    print(max(dp[3]))
    #print(dp[3][:30])
else:
    C, D = [], []
    for a, b in zip(A, B):
        if a <= b:
            C.append([a,b])
        else:
            D.append([b, a])

    if len(C)==1:
        a, b = C[0]
        q, n = divmod(N, a)
        N_ = q*b + n
    else:
        N_ = N
        (a1, b1), (a2, b2) = C
        for i in range(N + 1):
            j = N - i
            q1, n1 = divmod(i, a1)
            q2, n2 = divmod(j, a2)
            N_ = max(N_, q1 * b1 + q2 * b2 + n1 + n2)

    if len(D)==1:
        a, b = D[0]
        q, n = divmod(N_, a)
        print(q*b + n)
        #print("a")
    else:
        assert False
        ans = N_
        (a1, b1), (a2, b2) = D
        for i in range(N_+1):
            j = N_ - i
            q1, n1 = divmod(i, a1)
            q2, n2 = divmod(j, a2)
            ans = max(ans, q1*b1+q2*b2+n1+n2)
        print(ans)

Submission status: Runtime Error

Solution code:
import ortoolpy

N = int(input())

a = list(map(int,input().split()))
b = list(map(int,input().split()))

res = ortoolpy.knapsack(a,b,N)
res = ortoolpy.knapsack(b,a,int(res[0]))

print(str(int(res[0])))

Submission status: Runtime Error

Solution code:
def inpl(): return list(map(int, input().split()))
N = int(input())
GA = inpl()
GB = inpl()

typ = [GA[i] <= GB[i] for i in range(3)]

if sum(typ) == 3:
    ans = 0
    for g in range(N//GA[0] + 1):
        D = N - GA[0]*g
        for s in range(D//GA[1] + 1):
            b, D2 = divmod(D - GA[1]*s, GA[2])
            ans = max(ans, D2 + g*GB[0] + s*GB[1] + b*GB[2])

elif sum(typ) == 2:
    ans = 0
    x, y = typ.find(True), typ.rfind(True)
    z = typ.find(False)
    for a in range(N//GA[x] + 1):
        b, D = divmod(N - GA[x]*a, GA[y])
        c, D2 = divmod(D + GB[x]*a + GB[y]*b, GB[z])
        ans = max(ans, D2 + c*GA[z])

elif sum(typ) == 1:
    ans = 0
    x, y = typ.find(False), typ.rfind(False)
    z = typ.find(True)
    c, D = divmod(N, GA[z])
    D += GB[z]*c

    for a in range(D//GB[x] + 1):
        b, D2 = divmod(D-GB[x]*a, GB[y])
        ans = max(ans, D2 + GA[x]*a + GB[y]*b)

else:
    ans = 0
    for g in range(N//GB[0] + 1):
        D = N - GB[0]*g
        for s in range(D//GB[1] + 1):
            b, D2 = divmod(D - GB[1]*s, GB[2])
            ans = max(ans, D2 + g*GA[0] + s*GA[1] + b*GA[2])

print(ans)

Submission status: Runtime Error

Solution code:

from ortoolpy import knapsack

N = int(input())

a = list(map(int,input().split()))
b = list(map(int,input().split()))

size = a
weight = b
capacity = N
res = knapsack(size,weight,capacity)

N = int(res[0])

size = b
weight = a
capacity = N
res = knapsack(size,weight,capacity)

print(str(int(res[0])))

Submission status: Runtime Error

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
def nap(N,goods):
    dp=[-1*float('inf')]*(N+1)
    dp[0]=0
    for i in range(N):
        for w,v in goods:
            if i+w<=N:
                dp[i+w]=max(dp[i+w],dp[i]+v)
    return max([dp[i]+N-i for i in range(N+1)])
goods1=[(a,b) for a,b in zip(A,B) if a<b]
goods2=[(b,a) for a,b in zip(A,B) if a>b]
N=nap(N,[(a,b) for a,b in zip(A,B)])
if len(goods2)==0:
    print(N)
elif len(goods2)==1:
    print(N%goods2[0]+(N//goods2[0])*goods2[1])
elif len(goods2)==3:
    print(nap(N,goods2))
else:
    a,b,c,d=goods2[0][0],goods2[0][1],goods2[1][0],goods2[1][1]
    if b-a<d-c:
        a,b=c,d
    elif b-a==d-c and a>c:
        a,b=c,d
    bord=(N//a)*b+((N%a)//c)*d
    x=N//a
    ans=bord
    for i in range(1,1+x):
        now=(x-i)*b+((N-(x-i)*a)//c)*d
        if now+d<bord:
            break
        else:
            ans=max(ans,now)
    print(ans)

Submission status: Runtime Error

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
def nap(N,goods):
    dp=[-1*float('inf')]*(N+1)
    dp[0]=0
    for i in range(N):
        for w,v in goods:
            if i+w<=N:
                dp[i+w]=max(dp[i+w],dp[i]+v)
    return max([dp[i]+N-i for i in range(N+1)])
goods1=[(a,b) for a,b in zip(A,B) if a<b]
goods2=[(b,a) for a,b in zip(A,B) if a>b]
N=nap(N,[(a,b) for a,b in zip(A,B)])
if len(goods2)==0:
    print(N)
elif len(goods2)==1:
    print(N%goods2[0]+(N//goods2[0])*goods2[1])
elif len(goods2)==3:
    print(nap(N,goods2))
else:
    a,b,c,d=goods2[0][0],goods[0][1],goods[1][0],goods[1][1]
    if b-a<d-c:
        a,b=c,d
    elif b-a==d-c and a>c:
        a,b=c,d
    bord=(N//a)*b+((N%a)//c)*d
    x=N//a
    ans=bord
    for i in range(1,1+x):
        now=(x-i)*b+((N-(x-i)*a)//c)*d
        if now+d<bord:
            break
        else:
            ans=max(ans,now)
    print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
for i in range(2):
    a,b,c = map(int,input().split())
A=a[1]-a[0]
B=b[1]-b[0]
C=c[1]-c[0]
list = [A,B,C]
Maximam=max(list)+1
print(n*Maximam)

Submission status: Runtime Error

Solution code:
n=int(input())
for i in range(2):
    a,b,c = map(int,input().split())
A=a[1]-a[0]
B=b[1]-b[0]
C=c[1]-c[0]
list = [A,B,C]
Maximam=max(list)
print(n*Maximam)

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
aHIKUb=[[i,(a[i]-b[i])/a[i],(a[i]-b[i])/b[i]] for i in range(3)]
aHIKUb.sort(key=lambda x:x[1])
changeCnt=[0,0,0]
changeCnt[aHIKUb[0][0]]=n//a[aHIKUb[0][0]]
for i,aibi in aHIKUb[1:]:
    remain=n
    for j in range(3):
        remain-=a[j]*changeCnt[j]
    if aibi<0 and remain>a[i]:
        changeCnt[i]=remain//a[i]
for i in range(3):
    n+=(-a[i]+b[i])*changeCnt[i]

aHIKUb.sort(key=lambda x:x[2])
changeCnt=[0,0,0]
changeCnt[aHIKUb[2][0]]=n//b[aHIKUb[2][0]]
for i,aibi in aHIKUb[:2]:
    remain=n
    for j in range(3):
        remain-=a[j]*changeCnt[j]
    if aibi>0 and remain>a[i]:
        changeCnt[i]=remain//a[i]
for i in range(3):
    n+=(a[i]-b[i])*changeCnt[i]
print(n)

Submission status: Runtime Error

Solution code:
N = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())

dg = gb - ga
ds = sb - sa
db = bb - ba

arate = [ga, sa, ba]
brate = [gb, sb, bb]
ds = [dg, ds, db]

bestNafter = N

for i in range(3):
    if ds[i] > 0:
        rm1 = N % arate[i]
        gain1 = N // arate[i] * ds[i]
        if gain1 > 0 and rm1 > 0:
            for j in range(3):
                if j != i and ds[j] > 0:
                    rm2 = rm1 % arate[j]
                    gain2 = rm1 // arate[j] * ds[j]
                    if gain2 > 0 and rm2 > 0:
                        for k in range(3):
                            if k != i and k != j and ds[k] > 0:
                                rm3 = rm2 % arate[k]
                                gain3 = rm2 // arate[k] * ds[k]
                                Nafter = rm3 + gain1 + gain2 + gain3
                    else:
                        Nafter = rm2 + gain1 + gain2
        else:
            Nafter = rm1 + gain1
    else:
        Nafter = N
    bestNafter = max(bestNafter, Nafter)

N = bestNafter

bestNafter = N

for i in range(3):
    if ds[i] < 0:
        rm1 = N % brate[i]
        gain1 = N // brate[i] * (-ds[i])
        if gain1 > 0 and rm1 > 0:
            for j in range(3):
                if j != i and ds[j] < 0:
                    rm2 = rm1 % brate[j]
                    gain2 = rm1 // brate[j] * (-ds[j])
                    if gain2 > 0 and rm2 > 0:
                        for k in range(3):
                            if k != i and k != j and ds[k] < 0:
                                rm3 = rm2 % brate[k]
                                gain3 = rm2 // brate[k] * (-ds[k])
                                Nafter = rm3 + gain1 + gain2 + gain3
                    else:
                        Nafter = rm2 + gain1 + gain2
        else:
            Nafter = rm1 + gain1
    else:
        Nafter = N
    bestNafter = max(bestNafter, Nafter)

print(bestNafter)

Submission status: Runtime Error

Solution code:
// includes {{{
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<tuple>
#include<cmath>
#include<random>
#include<cassert>
#include<bitset>
#include<cstdlib>
// #include<deque>
// #include<multiset>
// #include<cstring>
// #include<bits/stdc++.h>
// }}}
using namespace std;
using ll = long long;

// #undef DEBUG
// #define DEBUG
// DEBUG {{{
#include <array>
#include <deque>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <valarray>
#include <vector>
template < int n, class... T >
typename std::enable_if< (n >= sizeof...(T)) >::type __output_tuple(
    std::ostream &, std::tuple< T... > const &) {}
template < int n, class... T >
typename std::enable_if< (n < sizeof...(T)) >::type __output_tuple(
    std::ostream &os, std::tuple< T... > const &t) {
  os << (n == 0 ? "" : ", ") << std::get< n >(t);
  __output_tuple< n + 1 >(os, t);
}
template < class... T >
std::ostream &operator<<(std::ostream &os, std::tuple< T... > const &t) {
  os << "(";
  __output_tuple< 0 >(os, t);
  os << ")";
  return os;
}
template < class T, class U >
std::ostream &operator<<(std::ostream &os, std::pair< T, U > const &p) {
  os << "(" << p.first << ", " << p.second << ")";
  return os;
}
template < class T >
std::ostream &operator<<(std::ostream &os, const std::stack< T > &a) {
  os << "{";
  for(auto tmp = a; tmp.size(); tmp.pop())
    os << (a.size() == tmp.size() ? "" : ", ") << tmp.top();
  os << "}";
  return os;
}
template < class T, class Container, class Compare >
std::ostream &operator<<(std::ostream &os,
    std::priority_queue< T, Container, Compare > a) {
  os << "{ (top) ";
  while(a.size()) os << a.top() << (a.size() == 1 ? "" : ", "), a.pop();
  os << " }";
  return os;
}
template < class T, class Container >
std::ostream &operator<<(std::ostream &os, std::queue< T, Container > a) {
  os << "{ ";
  while(a.size()) os << a.front() << (a.size() == 1 ? "" : ", "), a.pop();
  os << " }";
  return os;
}
#ifdef DEBUG
#if !defined(DEBUG_OUT)
// #define DEBUG_OUT std::cerr
#endif
#define dump(...)                                                                \
  [&]() {                                                                        \
    auto __debug_tap = std::make_tuple(__VA_ARGS__);                             \
    DEBUG_OUT << "[" << __LINE__ << "] " << #__VA_ARGS__ << " = " << __debug_tap \
    << std::endl;                                                      \
  }()
template < class T >
inline void dump2D(T &d, size_t sizey, size_t sizex) {
  for(size_t i = 0; i < sizey; i++) {
    DEBUG_OUT << "\t";
    for(size_t j = 0; j < sizex; j++)
      DEBUG_OUT << d[i][j] << (j + 1 == sizex ? "" : "\t");
    DEBUG_OUT << std::endl;
  }
}
template < class T >
inline void dump1D(T &d, size_t sizey) {
  for(size_t i = 0; i < sizey; i++) {
    DEBUG_OUT << d[i] << (i + 1 == sizey ? "" : " ");
  }
  DEBUG_OUT << std::endl;
}
template <
class T, class = typename std::iterator_traits< decltype(begin(T())) >::value_type,
      class = typename std::enable_if< !std::is_same< T, std::string >::value >::type >
      std::ostream &operator<<(std::ostream &os, const T &a) {
        os << "{";
        for(auto ite = begin(a); ite != end(a); ++ite)
          os << (ite == begin(a) ? "" : ", ") << *ite;
        os << "}";
        return os;
      }
#else
#define dump(...) ((void) 42)
#define dump2D(...) ((void) 42)
#define dump1D(...) ((void) 42)
template <
class T, class = typename std::iterator_traits< decltype(begin(T())) >::value_type,
      class = typename std::enable_if< !std::is_same< T, std::string >::value >::type >
      std::ostream &operator<<(std::ostream &os, const T &a) {
        for(auto ite = begin(a); ite != end(a); ++ite)
          os << (ite == begin(a) ? "" : " ") << *ite;
        return os;
      }
#endif
// }}}


int n;
int g[2][3];


int main() {
  std::ios::sync_with_stdio(false), std::cin.tie(0);
  cin >> n;
  for(int i = 0; i < 2; i++) for(int j = 0; j < 3; j++) cin >> g[i][j];

  ll now = n;
  for(int k = 0; k < 2; k++) {
    dump(k);
    ll ans = now;
    for(ll i = 0; i <= 5000; i++) for(ll j = 0; j <= 5000; j++) {
      ll G = i * g[k][0];
      ll S = j * g[k][1];
      if(g[k][0] >= g[!k][0] && i) continue;
      if(g[k][1] >= g[!k][1] && j) continue;
      ll rest = now - (G + S);
      if(rest < 0) continue;
      dump(i, j, rest);
      ll res = i * g[!k][0] + j * g[!k][1];
      if(g[k][2] < g[!k][2]) {
        ll b = rest / g[k][2];
        res += b * g[!k][2];
        rest -= b;
      }
      res += rest;
      ans = max(res, ans);
    }
    now = ans;
  }

  cout << now << endl;
  return 0;
}

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    N = int(input())
    A = LI()
    B = LI()
    ans = []
    for a in A:
        for b in B:
            if a == b:
                continue
            if a > b:
                if N < b:
                    continue
                ans.append(N % b + (N//b)*a)
            if b > a:
                if N < a:
                    continue
                ans.append(N % a + (N//a)*b)
    print(max(ans))


main()

Submission status: Runtime Error

Solution code:
N = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())
if max(gb/ga, sb/sa, bb/ba) > 0:
        N = int(N*max(gb/ga, sb/sa, bb/ba))

if max(ga/gb, sa/sb, ba/bb) > 1:
        N = int(N*maxmax(ga/gb, sa/sb, ba/bb))

print(N)