Problem:


Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.



Sample input:
7
100 130 130 130 115 115 150


Sample output:
1685

Submission status: Accepted

Solution code:
INF = 10 ** 10
n = int(input())
a = [INF] + list(map(int, input().split())) + [-INF]
l = []
for i in range(n):
    if len(l) % 2 == 0:
        if a[i + 1] < a[i + 2]:
            l.append(a[i + 1])
    else:
        if a[i + 1] > a[i + 2]:
            l.append(a[i + 1])
t = 1000
for i in range(1, len(l), 2):
    t = t // l[i - 1] * l[i] + t % l[i - 1]
print(t)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    def uniq(arr):
        ret = [arr[0]]
        for a in arr[1:]:
            if ret[-1] == a:
                continue
            ret.append(a)
        return ret

    def compress(arr):
        if len(arr) <= 2:
            return arr
        ret = [arr[0]]        
        for a0, a1, a2 in zip(arr, arr[1:], arr[2:]):
            if a0 < a1 < a2 or a0 > a1 > a2:
                continue
            ret.append(a1)
        ret.append(arr[-1])
        return ret

    B = uniq(A)
    C = compress(B)
    if len(C) == 1:
        return 1000
    ans, m, s = 1000, 1000, 0
    for c0, c1 in zip(C, C[1:]):
        if c0 < c1:
            t = m // c0
            s += t
            m -= t * c0
        else:
            m += c0 * s
            s = 0
        ans = max(ans, m)
    else:
        m += c1 * s
        ans = max(ans, m)
    return ans

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    print(solve(N, A))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
def lispin(t=int):return list(pin(t))
#%%code
def resolve():
    N,=pin()
    A=[*pin()]

    mon=1000
    stocks=0
    final=0
    for i in range(N-1):

        if A[i]>A[i+1]:# sell
            if stocks>0:
                #print("yaa")
                mon+=stocks*A[i]
                stocks=0
            final=0
            
        elif A[i]<A[i+1]: #buy

            stocks+=mon//A[i]
            mon=mon%A[i]
            final=1
        #print(mon,stocks)
    print(mon+stocks*A[-1])
            
#%%submit!
resolve()

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()

n = int(input())
As = map(int, input().split(" "))

status = None
start_A = None
cur = 1000
for i, A in enumerate(As):
    if i == 0:
        pass
    else:
        if last_A < A:
            if status is None or status == "down":
                start_A = last_A
                status = "up"

        elif last_A > A:
            if status == "up":
                end_A = last_A
                r = cur // start_A
                q = cur % start_A
                cur = r * end_A + q
                start_A = None
                status = "down"

    last_A = A

if start_A is not None:
    end_A = last_A
    r = cur // start_A
    q = cur % start_A
    cur = r * end_A + q
    start_A = None
   
print(cur)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
now = 1000
kab = 0
for i in range(n-1):
    if a[i] < a[i+1]:
        kab += now//a[i]
        now = now%a[i]
    if a[i+1] < a[i]:
        now += a[i]*kab
        kab = 0
now += a[-1]*kab
print(now)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
num=1000
num2=0
num3=-1
for i in range(n-1):
    if a[i]<a[i+1] and num3==-1:
        num2+=num//a[i]
        num-=a[i]*(num//a[i])
        num3=a[i+1]
    elif num3!=-1:
        if a[i]<a[i+1]:
            num3=a[i+1]
        if a[i]>a[i+1]:
            num+=a[i]*num2
            num2=0
            num3=-1
num+=max(a[-1],a[-2])*num2
print(num)

Submission status: Accepted

Solution code:
# import sys
# input = sys.stdin.readline

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


# ランレングス圧縮
def rle(lst):
    ans = []
    cnt = 1
    ini = lst[0]
    for i in range(1, len(lst)):
        if ini == lst[i]:
            cnt += 1
        else:
            ans.append((ini, cnt))
            cnt = 1
            ini = lst[i]
    ans.append((ini, cnt))
    return ans

n = int(input())
a = lmp()
t = ["d"]
for i in range(1,n):
    if a[i] >= a[i-1]:
        t.append("u")
    else:
        t.append("d")
rt = rle(t)
if rt[-1][0] == "d":
    rt = rt[:-1]
cum = -1
money = 1000
kabu = 0
for i in range(len(rt)):
    if i % 2 == 0:
        cum += rt[i][1]
        kabu = money//a[cum]
        money -= kabu * a[cum]
    else:
        cum += rt[i][1]
        money += kabu * a[cum]
        kabu = 0
print(money)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
t=1000
for i in range(n-1):
    if a[i]<a[i+1]:
        tmp=t//a[i]
        tmp1=tmp*a[i+1]
        t+=tmp1-tmp*a[i]
print(t)

Submission status: Accepted

Solution code:
n = int(input())
A = [int(i) for i in input().split()]
B = [A[0]]
for i in range(n - 2):
    if (B[-1] <= A[i + 1] <= A[i + 2]) | (B[-1] >= A[i + 1] >= A[i + 2]):
        continue
    else:
        B.append(A[i + 1])
if B[-1] < A[-1]:
    B.append(A[-1])
if len(B) > 1:
    if B[0] > B[1]:
        B = B[1:]
if len(B) % 2 == 1:
    B = B[:-1]
money = 1000
now = 0
for i in range(len(B) - 1):
    if B[i] < B[i + 1]:
        now += money // B[i]
        money -= (money // B[i]) * B[i]
    else:
        money += now * B[i]
        now = 0
if len(B) > 0:
    money += now * B[-1]    
print(money)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

stock = 0
money = 1000
for i in range(N-1):
    if A[i+1] >= A[i]:
        stock += money // A[i]
        money = money % A[i]
    else:
        money += stock * A[i]
        stock = 0

ans = money + stock * A[-1]
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
prices = list(map(int, input().split()))

cash = 1000

low_p = prices[0]
share = cash // low_p

for price in prices:
    if low_p > price:
        low_p = price
        share = cash // price

    if low_p < price:
        cash += (price - low_p) * share
        low_p = price

print(cash)

Submission status: Accepted

Solution code:
from sys import stdin
input = stdin.readline

N = int(input())
A = list(map(int, input().split()))

start = 0
money = 1000

for i in range(N - 1):
    if A[i + 1] > A[i]:
        tmp = 10 ** 3
        for k in range(i, start - 1, -1):
            tmp = min(A[k], tmp)
        buy = money // tmp
        money -= tmp * buy
        money += buy * A[i + 1]
        start = i + 1

print(money)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n = inp()
a = inpl()
hav = []
res = 1000
for x in a:
    # print(res)
    for y,c in hav:
        res = max(res,y*x+c)
    yy = res//x
    cc = res - yy*x
    hav.append([yy,cc])
# print(hav)
print(res)

Submission status: Accepted

Solution code:
n = int(input())
li_a = list(map(int, input().split()))
m = 1000
a = 0
for i in range(n-1):
    if li_a[i] < li_a[i+1]:
        a = m//li_a[i]
        m -= a*li_a[i]
        m += a*li_a[i+1]
    else:
        continue
print(m)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


def run_length_encoding(s):
    '''連長圧縮を行う
    s ... iterable object e.g. list, str 
    return
    ----------
    s_composed,s_num,s_idx
    それぞれ、圧縮後の文字列、その文字数、その文字が始まるidx'''
    s_composed, s_sum = [], []
    s_idx = [0]
    pre = s[0]
    cnt = 1
    for i, ss in enumerate(s[1:], start=1):
        if pre == ss:
            cnt += 1
        else:
            s_sum.append(cnt)
            s_composed.append(pre)
            s_idx.append(i)
            cnt = 1
            pre = ss
    s_sum.append(cnt)
    s_composed.append(pre)
    # assert len(s_sum) == len(s_composed)
    return s_composed, s_sum, s_idx


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce

N = a_int()
A = ints()

# 原則安いときに買って高いときに売る
# 複利の計算が入るのがめんどいな
# 極大極小みつけて売り買いかな
# 同じ金額の日は無いも等しいので消しちゃうか
A, _, _ = run_length_encoding(A)
A = [400] + A + [0]
# print(A)

torihiki = []
for i in range(len(A) - 2):
    if A[i] > A[i + 1] and A[i + 1] < A[i + 2]:
        torihiki.append(A[i + 1])
    elif A[i] < A[i + 1] and A[i + 1] > A[i + 2]:
        torihiki.append(A[i + 1])

# 愚直シミュレーション
en = 1000
kabu = 0

for i, a in enu(torihiki):
    if i & 1:  # 売る
        en += kabu * a
        kabu = 0
    else:  # 買う
        kabu = en // a
        en %= a
print(en)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

buy = [0] # 買う日
sell = [] # 売る日

target = 0
i = 1
while i < n:
    if a[i] >= a[i-1]:
        # 売らなくていい
        if i == n-1:
            # 最終日なので売る
            sell.append(i)
    else:
        # 売るべき
        sell.append(i-1)
        buy.append(i)
    i += 1
# print(buy, sell)

money = 1000 # 現金
stock = 0 # 株
for i in range(n):
    # print(money, stock)
    if i in buy and i != n-1:
        if not i in sell:
            stock += money // a[i]
            money = money % a[i]
    elif i in sell:
        if not i in buy:
            money += stock*a[i]
            stock = 0
print(money)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int, input().split()))+[0]

i=0
kane=1000
kabu=0
while i<N:
  if kabu==0:
    if A[i]<A[i+1]:
      kabu=kane//A[i]
      kane=kane%A[i]
    else:
      pass
  else:
    if A[i]>A[i+1]:
      kane=kane+kabu*A[i]
      kabu=0
    else:
      pass
  i+=1
  
print(kane)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))

f = [0]*N
for i in range(N-1):
    if A[i]<A[i+1]:
        f[i] = 1
    elif A[i]>A[i+1]:
        f[i] = -1

ans = 1000
for s in range(N):
    for t in range(s,N):
        m = 1000%A[s]
        n = 1000//A[s]
        for i in range(s+1,t):
            if f[i]==1:
                n += m//A[i]
                m %= A[i]
            elif f[i]==-1:
                m += A[i]*n
                n = 0
        m += n*A[t]
        ans = max(ans,m)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
*arr, = map(int, input().split())

compressed = []

mx = max(arr)

start = 0
for i, v in enumerate(arr):
    if i == len(arr) - 1 or arr[i + 1] < arr[i]:
        compressed.append((arr[start], arr[i]))
        start = i + 1

ans = 1000
for start, end in compressed:
    ans = (ans // start * end) + ans % start

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
m = 1000
k = 0
i=0
while i < n:
    f=1
    for j in range(i + 1, n):
        if a[i] < a[j]:
            f=0
            k += m // a[i]
            m %= a[i]
            m += a[j] * k
            k=0
            i = j
        else:
            break
    if f:
        i += 1
print(m)

Submission status: Accepted

Solution code:
N = int(input())
A = [201] + list(map(int, input().split())) + [99]
UD = []

cnt = 0
temp = 1000

for i in range(N+1):
  if A[i] >= A[i+1]:
    UD.append(-1)
  else:
    UD.append(1)

for i in range(N):
  if UD[i] < UD[i+1]:
    cnt, temp = divmod(temp, A[i+1])
  if UD[i] > UD[i+1]:
    temp, cnt = temp + cnt * A[i+1], 0

print(temp)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
X=1000
for i in range(1,N):
    if A[i-1]<A[i]:
        stock=X//A[i-1]
        X=X-stock*A[i-1]+stock*A[i]
print(X)

Submission status: Accepted

Solution code:
N, *A = map(int, open(0).read().split())
rising_terms = []
tmp = []
for i in range(N - 1):
    if A[i] < A[i + 1]:
        tmp.append(A[i])
    elif tmp:
        rising_terms.append(tmp + [A[i]])
        tmp = []
if A[N - 2] < A[N - 1]:
    rising_terms.append(tmp + [A[N - 1]])
ans = 1000
for rising_term in rising_terms:
    stock, r_money = divmod(ans, rising_term[0])
    ans = r_money + stock * rising_term[-1]
print(ans)

Submission status: Accepted

Solution code:
import sys


def handler():
    n = int(input().strip())
    a = [int(i) for i in input().strip().split()]
    cash, stock = 1000, 0
    buyin = 0
    for i in range(n):
        if stock > 0:
            # sys.stderr.write('[%d] sold %d (buyin = %d)\n' % (i, stock, buyin))
            cash += stock * max(buyin, a[i])
            stock = 0
        if i < n - 1 and cash >= a[i] and a[i] <= max(a[i + 1:]):
            buyin = a[i]
            k = cash // a[i]
            cash -= k * a[i]
            stock += k
            # sys.stderr.write('[%d] buy %d\n' % (i, k))
        # sys.stderr.write('%d, %d\n' % (cash, stock))
    sys.stdout.write('%d\n' % cash)


def main():
    while True:
        try:
            handler()
        except ValueError:
            continue
        except EOFError:
            break


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

money = 1000
stock = 0
for i in range(N-1):
    # print(money, stock)
    if A[i] < A[i+1]:
        # 明日あがるなら買えるだけ買う
        buy = money // A[i]
        stock += buy
        money -= A[i] * buy
    elif A[i] == A[i+1]:
        # 変わらないなら何もしない
        pass
    else:
        # 明日下がるなら全部売る
        sell = stock
        stock = 0
        money += A[i] * sell

sell = stock
stock = 0
money += A[-1] * sell

print(money)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))

m = 1000
cnt = 0
have = False
for i in range(n-1):
    if cnt:
        if a[i] >= a[i+1]:
            m += cnt * a[i]
            cnt = 0
    else:
        if a[i] < a[i+1]:
            cnt += m // a[i]
            m -= a[i] * cnt
m += cnt * a[n-1]

print(m)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
M = []
m = []
if A[0] <= A[1]:
        m.append(A[0])
for i in range(N-2):
    if A[i+1] >= A[i] and A[i+1] > A[i+2]:
        M.append(A[i+1])
    elif A[i+1] < A[i] and A[i+1] <= A[i+2]:
        m.append(A[i+1])
if A[N-1] >= A[N-2]:
    M.append(A[N-1])
now = 1000
kabu = 0
for i in range(len(m)):
    kabu += now//m[i]
    now -= kabu*m[i]
    now += kabu*M[i]
    kabu = 0
print(now)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

N = int(input())
A = list(map(int, input().split()))

n_kabu = 0
shojikin = 1000
is_upper = False
is_under = False
for n in range(0,N-1):
    if not is_upper and A[n] < A[n+1]:
        is_upper = True
        is_under = False
        # 購入
        n_kabu = int(shojikin/A[n])
        shojikin -= n_kabu*A[n]
    elif not is_under and A[n] > A[n+1]:
        is_under = True
        is_upper = False
        # 売却
        shojikin += n_kabu*A[n]
        n_kabu = 0

print(shojikin+(n_kabu*A[N-1]))

Submission status: Accepted

Solution code:
import numpy as np

money = 1000
kabu = 0

n = int(input())

a = np.array(list(map(int, input().split())))

for i in range(n-1):
  if a[i] < a[i+1]:
    kabu += int(money/a[i])
    money = money%a[i]

  elif a[i] > a[i+1]:
    money += kabu*a[i]
    kabu = 0

print(money+kabu*a[-1])

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
stock =0
money = 1000
for i in range(n-1):
    if A[i]<A[i+1]:
        stock += money//A[i]
        money -= (money//A[i])*A[i]
        #買う
    elif A[i]>A[i+1]:
        money += stock*A[i]
        stock =0
        #うる
    else:
        continue
if stock >0:
    money += stock*A[-1]
print(money)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

n=II()
aa=[1000]+LI()
m=1000
k=0
up=False
for i in range(1,n+1):
    if up and aa[i-1]>aa[i]:
        m+=k*aa[i-1]
        k=0
        up=False
    elif up==False and aa[i-1]<aa[i]:
        k+=m//aa[i-1]
        m-=aa[i-1]*k
        up=True
    #print(i,m,k)
m+=aa[-1]*k
print(m)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

pairs = []
low = None
if a[0] < a[1]:
	low = a[0]

for i in range(1, n):
	if a[i-1] > a[i]:
		if low is not None:
			pairs.append((low, a[i-1]))
			low = a[i]
	if a[i-1] < a[i]:
		if low is None:
			low = a[i-1]
if low is not None and low < a[n-1]:
	pairs.append((low, a[n-1]))

yen = 1000
for (l, h) in pairs:
	size = yen // l
	yen -= size * l
	yen += size * h
print(yen)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain, product
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    # 10**6
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     # 10**6
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):
    return fs[n] * invs[n-k] * invs[k] % modp

#

class UnionFindEx:
    def __init__(self, size):
        #正なら根の番号、負ならグループサイズ
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   #負なら根
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    #サイズ更新
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'


def main():
    N = ii()
    A = lmis()
    dp = [1000] * N
    for i in range(1, N):
        for j in range(i):
            m = dp[j]
            s = m//A[j]
            m %= A[j]
            m += s*A[i]
            dp[i] = max(dp[i], m, dp[j])
    print(dp[-1])







main()

Submission status: Accepted

Solution code:
import sys

def solve():
      input = sys.stdin.readline
      N = int(input())
      A = [int(a) for a in input().split()]
      total = 1000
      stock = 0
      status = -1 #1なら増加,-1なら減少
      for i in range(1, N):
            if A[i] > A[i-1]:
                  if status == -1:
                        stock = total // A[i-1]
                        total -= stock * A[i-1]
                        status = 1
            elif A[i] < A[i-1]:
                  if status == 1:
                        total += stock * A[i-1]
                        stock = 0
                        status = -1
      if stock > 0:
            total += stock * A[N-1]
      print(total)


      return 0

if __name__ == "__main__":
      solve()

Submission status: Accepted

Solution code:
from copy import deepcopy
def resolve():
    N = int(input())
    A = list(map(int,input().split()))
    tbl = dict()
    tbl[0]= 1000
    for i in A:
        ntbl = deepcopy(tbl)
        for kabu,yen in tbl.items():
            ny = yen + kabu * i
            nk = 0
            if not nk in ntbl or ntbl[nk]<ny:
                ntbl[nk]=ny

            nk = yen // i + kabu
            ny = yen % i
            if not nk in ntbl or ntbl[nk]<ny:
                ntbl[nk]=ny
        tbl = ntbl
    print(max(tbl.values()))    
    

resolve()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

new_A = []
prev_a = -1
for a in A:
    if prev_a == a:
        continue
    new_A.append(a)
    prev_a = a

stock = 0
wallet = 1000
for i in range(len(new_A)):
    prev_price = 201 if i == 0 else new_A[i - 1]
    next_price = 0 if i == len(new_A) - 1 else new_A[i + 1]
    #print(prev_price, new_A[i], next_price)
    # 極大
    if prev_price < new_A[i] and next_price < new_A[i]:
        # 売る
        #print('sell: ' + str(new_A[i]) + ' * ' + str(stock))
        wallet += stock * new_A[i]
        stock = 0
    if new_A[i] < prev_price and new_A[i] < next_price:
        # 買う
        #print('buy: ' + str(new_A[i]) + ' * ' + str(wallet // new_A[i]))
        stock = wallet // new_A[i]
        wallet = wallet % new_A[i]
print(wallet)

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())
a =np.array([int(x) for x in input().split()])

money = 1000
stock = 0

for i in range(n-1):
    if a[i] < a[i+1]:
        stock += money//a[i]
        money %= a[i]
    elif a[i] > a[i+1]:
        money += a[i]*stock
        stock = 0

money += a[-1]*stock

print(money)

Submission status: Accepted

Solution code:
n=int(input())
A=[int(i) for i in input().split()]
T=[]

flg=-1
for i in range(n-1):
    if A[i]<A[i+1] and flg==-1:
        flg=1
        T.append(A[i])
    elif A[i]>A[i+1] and flg==1:
        flg=-1
        T.append(A[i])

if A[-2]<=A[-1]:
    T.append(A[-1])

kab=0
mon=1000

for i in range(len(T)):
    if i%2==0:
        kosuu=mon//T[i]
        kab+=kosuu
        mon-=kosuu*T[i]
    else:
        mon+=kosuu*T[i]
        kab=0

if len(T)>0:
    mon+=kab*T[i]

print(mon)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
c = [a[0]]
l = []
h = 1000
for i in range(1, n):
    if a[i - 1] > a[i]:
        l.append(c)
        c = [a[i]]
    else:
        c.append(a[i])
l.append(c)
for i in l:
    cnt = h // i[0]
    h %= i[0]
    h += i[-1] * cnt
print(h)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    ans = [1000]*n
    for i in range(n):
        kabu = ans[i]//a[i]
        amari = ans[i] % a[i]
        for j in range(i+1, n):
            if ans[j] < kabu*a[j] + amari:
                ans[j] = kabu*a[j] + amari
            if ans[j] < ans[i]:
                ans[j] = ans[i]
    print(ans[-1])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))

stock = 0
money = 1000

for i in range(n):
    if i == n-1:
        if stock:
            money += stock*a[i]
    elif stock:
        if a[i] > a[i+1]:
            money += stock*a[i]
            stock = 0
        else:
            pass
    else:
        if a[i] < a[i+1]:
            stock += money//a[i]
            money -= stock*a[i]
        else:
            pass

print(money)

Submission status: Accepted

Solution code:
N = int(input())
a = input().split()
A = [int(u) for u in a]
cur = 1000
sto = 0
for i in range(1, N):
	if A[i] > A[i - 1]:
		b = cur // A[i - 1]
		sto += b
		cur -= b * A[i - 1]
		cur += sto * A[i]
		sto = 0
	else:
		cur += sto * A[i - 1]
		sto = 0
		b = cur // A[i]
		sto += b
		cur -= b * A[i]

if not sto == 0:
	cur += sto * A[N - 1]

print(cur)

Submission status: Accepted

Solution code:
n = int( input() )
a = list( map( int, input().split() ) )

money = 1000
kabu = 0

a.append( -1 )
c = [ 0 for _ in range( n + 1 ) ]
for i in range( n ):
    if a[ i ] < a[ i + 1 ]:
        c[ i ] = 1
    elif a[ i ] == a[ i + 1 ]:
        c[ i ] = 0
    else:
        c[ i ] = -1

for i in reversed( range( n ) ):
    if c[ i ] == 0:
        c[ i ] = c[ i + 1 ]

for d in range( n ):
    if c[ d ] > 0:
        kabu += money // a[ d ]
        money = money % a[ d ]
    else:
        money += kabu * a[ d ]
        kabu = 0

print( money )

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
kabu = 0
m = 1000
for i in range(1,n):
    if a[i] > a[i-1] and kabu == 0:
        kabu = m//a[i-1]
        m -= kabu*a[i-1]
        #print(m,kabu)
        continue
    elif a[i] < a[i-1] and kabu != 0:
        m += kabu*a[i-1]
        kabu = 0
        #print(m,kabu)
        continue
if kabu != 0:
    m += kabu*a[-1]
print(m)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
import copy
# from fractions import gcd

MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)

n = int(input())
A = list(map(int, input().split()))

state = 0
money = 1000
stock = 0
for i in range(n-1):
    if A[i] < A[i+1] and state == 0:
        stock = money // A[i]
        money = money % A[i]
        state = 1
    elif A[i] > A[i+1] and state == 1:
        money += stock*A[i]
        stock = 0
        state = 0
    # print(state, money, stock)

if state == 1:
    money += stock * A[-1]

print(money)

Submission status: Accepted

Solution code:
ans=1000
N=int(input())
A=list(map(int,input().split()))
for i in range(N-1):
    if A[i]<A[i+1]:
        ans+=(ans//A[i])*(A[i+1]-A[i])
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy


def solve(arr):  # fix inputs here
    console("----- solving ------")
        

    brr = [arr[0]]

    for a in arr[1:]:
        if a == brr[-1]:
            continue
        brr.append(a)

    brr = [999] + brr + [0]

    console(brr)

    pos = []
    neg = []
    
    for a,b,c in zip(brr, brr[1:], brr[2:]):
        if a < b and b > c:
            pos.append(b)
        elif a > b and b < c:
            neg.append(b)
        
    console(pos, neg)

    cash = 1000
    for n,p in zip(neg, pos):
        stock_bought = cash//n
        gains = stock_bought * (p-n)
        cash = cash + gains


    # return a string (i.e. not a list or matrix)
    return cash


def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
# sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    _ = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    lst = list(map(int,input().split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    # grid = []
    # for _ in range(nrows):
    #     grid.append(list(map(int,input().split())))

    res = solve(lst)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)