jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
fn main() {
    let line = read::<i128>();
    let mut current_pos = line[0];
    let mut move_cnt = line[1];
    let move_distance = line[2];
    // skip
    let skip_cnt = current_pos.abs() / move_distance;
    let skippable_distance = move_distance * skip_cnt;
    if skip_cnt >= move_cnt {
        let tyouka = skip_cnt - move_cnt;
        let actual_distance = skippable_distance - tyouka * move_distance;
        println!("{}", current_pos.abs() - actual_distance);
        return;
    }
    move_cnt -= skip_cnt;
    current_pos -= skippable_distance;

    // move to nearest pos
    let mut prev_pos = current_pos;
    loop {
        if move_cnt == 0 {
            break;
        }
        if current_pos > 0 {
            current_pos = current_pos - move_distance;
        } else {
            current_pos = current_pos + move_distance;
        }
        move_cnt -= 1;
        if current_pos.abs() >= prev_pos.abs() {
            move_cnt += 1;
            current_pos = prev_pos;
            break;
        }
        prev_pos = current_pos;
    }
    if move_cnt == 0 {
        println!("{}", current_pos.abs());
        return;
    }
    // hanpukuyokotobi
    if move_cnt % 2 == 0 {
        println!("{}", current_pos.abs());
    } else {
        let current_pos = if current_pos > 0 {
            current_pos - move_distance
        } else {
            current_pos + move_distance
        };
        println!("{}", current_pos.abs());
    }
}

use std::io::{self, BufRead, Read};
use std::vec::Vec;
fn read<T: std::str::FromStr>() -> Vec<T> {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.lock().read_line(&mut buf).unwrap();
    parse_line(&buf)
}

fn read_lines<T: std::str::FromStr>(count: usize) -> Vec<Vec<T>> {
    let stdin = io::stdin();
    let mut stdin = stdin.lock();
    let mut result = Vec::<Vec<T>>::with_capacity(count);
    for _ in 0..count {
        let mut buf = String::new();
        stdin.read_line(&mut buf).unwrap();
        result.push(parse_line(&buf));
    }
    result
}

fn parse_line<T: std::str::FromStr>(string: &str) -> Vec<T> {
    string.trim().split(' ').map(|s| T::from_str(s).ok().unwrap()).collect()
}
//  [swift]
func readThreeInts(separator: String.Element = " ") -> (a: Int, b: Int, c: Int) {
    let ints = readLine()!.split(separator: separator).map { Int($0)! }
    return (a: ints[0], b: ints[1], c: ints[2])
}

func mainC() {
    let (X, K, D) = readThreeInts()

    // いくら移動しても理論値に到達しない場合
    if abs(X) > abs(K * D) {
        print(abs(X) - abs(K * D))
        return
    }

    var position = X
    for i in 1...K {
        if abs(position - D) < abs(position) {
            position -= D
        } else if abs(position + D) < abs(position) {
            position += D
        } else {
            // 絶対値が大きくなってしまう場合
            let remain = K - i + 1
            // 2の倍数なら+D, -Dをし続けて消化できる
            if remain.isMultiple(of: 2) {
                break
            } else {
                // 2の倍数じゃないならより大きくならない方に移動して終わる
                if position >= 0 {
                    position -= D
                } else if position <= 0 {
                    position += D
                } else {
                    fatalError()
                }

                break
            }
        }
    }

    print(abs(position))
}
mainC()
//  [swift]
import Foundation

func main() {
    guard let line = readLine() else { return }
    let inputs = line.components(separatedBy: " ").compactMap() { Int($0) }
    let x = inputs[0]
    let k = inputs[1]
    let d = inputs[2]
    var tmp = 0
    
    if abs(x) / d < k {
        for i in 1...k {
            if abs(x) < i * d {
                tmp = i
                break
            }
        }
        if (k - tmp) % 2 == 0 {
            print(tmp * d - abs(x))
        } else {
            print(d - ((tmp * d) - abs(x)))
       }
    } else  {
        print(abs(x) - k * d)
    }
}


main()
//  [typescript]
// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [X, K, D] = r.nn()
    const xp = Math.abs(X)

    const plusMin = xp % D
    const minusMin = Math.abs((xp % D) - D)
    const steps = (xp - plusMin) / D

    const t = xp - K * D

    if (t >= 0) {
      return t
    }
    // console.log(sueps)
    // console.log(steps % 2)

    return Math.abs([plusMin, minusMin][(K - steps) % 2])
  }

  const _io = (i = 0) => {
    const str: string = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}
//  [typescript]
import * as fs from "fs";

const input = fs
  .readFileSync("/dev/stdin", "utf8")
  .split(" ")
  .map(Number);
// Xは今の座標
// Kは回数
// Dは移動距離
let X,K,D;

[X, K, D] = input;
// 負の場合も考えて絶対値に
X = Math.abs(X);
let ans;
// 原点を跨がないパターン
if(X >= D * K) {
  ans = X - K * D;
} else {
  // 往復までの回数
  let e = Math.floor(X/D);
  // 往復までにかかった分を引く
  K -= e;
  // 往復のポイント
  X -= e * D;
  // 跨ぐパターン
  if(K % 2 == 1){ 
    ans = Math.abs(X - D);
  } else {
  	ans = X;
  }
  
}
console.log(ans);
//  [python]
n=int(input())
a=list(map(int,input().split()))
ans=[1000]
m=1000
k=0
for i,num in enumerate(a):
	m=k*num+m
	k=0
	ans.append(m)
	if i<n-1:
		if num<a[i+1]:
			k=m//num
			m=m-k*num
print(max(ans))
//  [python]
def main():
    N = int(input())
    A = [int(_x) for _x in input().split()]

    kabu = 0
    kin = 1000
    for i in range(N):
        if kabu > 0:
            kin = kin + A[i] * kabu
            kabu = 0
        if i < N-1:
            if A[i] < A[i+1]:
                kabu = int(kin/A[i])
                kin = kin - A[i] * kabu
    print(kin)

main()
//  [python]
import sys
 
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))

m = 1000
for i in range(1, n):
    if a[i - 1] < a[i]:
        m = m % a[i-1] + m // a[i-1] * a[i];

print(m)
//  [python]
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    cur=1000
    curk=0
    for i,a in enumerate(A):
        if i==N-1:
            cur+=a*curk
            curk=0
            continue

        if a<=A[i+1]:
            x=cur//a
            curk+=x
            cur-=x*a
        else:
            cur+=a*curk
            curk=0
    print(cur)





if __name__ == "__main__":
    main()
//  [python]
import sys
import heapq
import math
import fractions
import bisect
import itertools
from collections import Counter
from collections import deque
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

n=int(input())
a=lmp()
a.insert(0,10000)
a.append(0)
i=0
m=len(a)
while i<m-1:
    if a[i]==a[i+1]:
        del a[i]
        i-=1
    i+=1
    m=len(a)

n=len(a)-2

l=[0]*(n+2)
for i in range(1,n+1):
    if a[i-1]<a[i]>a[i+1]:
        l[i]=1
    elif a[i-1]>a[i]<a[i+1]:
        l[i]=-1
sto=[0,1000]
for i in range(n+2):
    if l[n+1-i]==-1:
        l[n+1-i]=0
        break
    elif l[n+1-i]==1:
        break
for i in range(n+2):
    if l[i]==-1:
        sto[0],sto[1]=divmod(sto[1],a[i])
    if l[i]==1:
        sto[1]+=sto[0]*a[i]
        sto[0]=0
print(sto[1])
//  [java]
import java.util.*;
import java.io.*;

public class Main{

static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static int[] int_arr() throws IOException{String[] a=read().split("\\s+");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split("\\s+");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res;}
//......................................@uthor_Alx..............................................
static long mod=(long)1e9+7;

public static void main(String[] args) throws  IOException{
                assign();
                int n=int_v(read());
                int[] a=int_arr();
                long[][] dp=new long[n+1][4];
                dp[0][0]=1000l;
                for(int i=1;i<=n;i++){
                    dp[i][2]=dp[i-1][3]+(long)a[i-1]*dp[i-1][1];//sell all
                    long max=Math.max(dp[i-1][0],Math.max(dp[i-1][2],dp[i][2]));
                    dp[i][0]=max;// doing nothing
                    dp[i][1]= max/a[i-1];//buy all
                    dp[i][3]=max-(long)dp[i][1]*a[i-1];
                }
                out.write(Math.max(dp[n][0],dp[n][2])+"");
                out.flush();

    }
}
//  [java]
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {  
 
	public static void main(String[] args) { 
		FastScanner I = new FastScanner(); //Input
		OutPut O = new OutPut(); //Output
		int N = I.nextInt();
		long stocks = 0;
		long[] a = new long[N];
		for (int i = 0; i < N; i++) a[i] = I.nextLong();
		long price = a[0];
		long max = 0; //Highest local bidder
		long ans = 1000; //Money
		for (int i = 1; i < N; i++) {
			if (a[i]<a[i-1]&&max==0) price=a[i];
			else if (a[i]<a[i-1]&&max!=0) {
				stocks+=ans/price;
				ans%=price;
				ans+=stocks*max;
				stocks=0; //Sold all
				price=a[i];
				max=0;
			}
			else if (a[i]>a[i-1]) {
				max=a[i];
			}
		}
		//O.pln(ans);
		if (max>0) {
			stocks+=ans/price;
			ans%=price;
			ans+=stocks*max;
			stocks=0; //Sold all
			max=0;
		}
		O.pln(ans);
	}
	public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0) 
	ans++; return ans;}
	public static long GCD(long a, long b) {
		if (a==0||b==0) return Math.max(a,b);
		return GCD(Math.min(a, b),Math.max(a, b)%Math.min(a, b));
	}
	public static long FastExp(long base, long exp, long mod) {
		long ans=1;
		while (exp>0) {
			if (exp%2==1) ans*=base;
			exp/=2;
			base*=base;
			base%=mod;
			ans%=mod;
		}
		return ans;
	}
	public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);}
	public static int pop(long x) { //Returns number of bits within a number
		int cnt = 0;
		while (x>0) {
			if (x%2==1) cnt++;
			x/=2;
		}
		return cnt;
	}
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		int nextInt() {return Integer.parseInt(next());}
		long nextLong() {return Long.parseLong(next());};
		double nextDouble() {return Double.parseDouble(next());}
	}
	static class OutPut{
		PrintWriter w = new PrintWriter(System.out);
		void pln(double x) {w.println(x);w.flush();}
		void pln(boolean x) {w.println(x);w.flush();}
		void pln(int x) {w.println(x);w.flush();}
		void pln(long x) {w.println(x);w.flush();}
		void pln(String x) {w.println(x);w.flush();}
		void pln(char x) {w.println(x);w.flush();}
		void pln(StringBuilder x) {w.println(x);w.flush();}
		void pln(BigInteger x) {w.println(x);w.flush();}
		void p(int x) {w.print(x);w.flush();}
		void p(long x) {w.print(x);w.flush();}
		void p(String x) {w.print(x);w.flush();}
		void p(char x) {w.print(x);w.flush();}
		void p(StringBuilder x) {w.print(x);w.flush();}
		void p(BigInteger x) {w.print(x);w.flush();}
		void p(double x) {w.print(x);w.flush();}
		void p(boolean x) {w.print(x);w.flush();}
	}
}
//  [java]
import java.util.*;
import java.io.*;

public class Main {
	private static void solve(){
		//Implement solution here.
		int N = ni();
		int[] A = na(N);
		int[] trends = new int[N];
		long result = 1000;
		long stocks = 0;
		
		for(int i = 1; i < N; i++) {
			if(A[i] < A[i - 1]) {
				trends[i] = - 1;
			} else if(A[i] == A[i - 1]) {
				trends[i] = trends[i - 1];
			} else {
				trends[i] = 1;
			}
		}
		
		for(int i = N - 2; i >= 0; i--) {
			if(trends[i] == 0)trends[i] = trends[i + 1];
		}
		
		if(trends[1] > 0) {			
			stocks = result / A[0];
			result = result % A[0];			
		}
		
		for(int i = 1; i < N - 1; i++) {
			if(trends[i] > 0 && trends[i + 1] < 0) {
				//sell
				result += A[i] * stocks;
				stocks = 0;
			} else if (trends[i] < 0 && trends[i + 1] > 0) {
				//buy
				stocks = result / A[i];
				result = result % A[i];				
			}
		}
		
		result += A[N - 1] * stocks;
		stocks = 0;
		System.out.println(result);
//		for(int i:trends)System.out.print(i + " ");
//		System.out.println();
	}


	//Switch input source (stdin/file)
	private static BufferedReader br;
	public static void main(String[] args){
		br = new BufferedReader(new InputStreamReader(System.in));
		String debugDataPath = System.getenv("DD_PATH");        
		if(debugDataPath != null){
			try{
				br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(debugDataPath))));
			}catch(Exception e){
				throw new RuntimeException(e);
			}
		}
		boolean hasNext = true;
		while(hasNext){
			solve();	
			try{
				br.mark(1);
				if(br.read() > 0){
					br.reset();			
					System.out.println("---");
				} else {
					hasNext = false;
				}
			}catch(Exception e){
				throw new RuntimeException(e);
			} 
		}
	}

	//Input read utility
	private static StringTokenizer tokenizer = null;
	public static String next() {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			try {
				tokenizer = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken();
	}
	//Get next single int
	private static int ni() {
		return Integer.parseInt(next());
	}
	//Get next single long
	private static long nl() {
		return Long.parseLong(next());
	}
	//Get next single double
	private static double nd() {
		return Double.parseDouble(next());
	}
	//Get next int array from one line
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}
	//Get next char array from one line
	private static char[] ns() {
		return next().toCharArray();
	}
	//Get next long array from one line
	private static long[] nal(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}
}
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		long[] a = new long[n + 1];
		for(int i = 1 ; i <= n ; i++) {
			a[i] = sc.nextLong();
		}
		boolean katteru = false;
		long sum = 1000;
		long kabusuu = 0;
		for(int i = 2 ; i <= n ; i++) {
			if(!katteru) {
				if(a[i] > a[i - 1] && sum >= a[i - 1]) {
					katteru = true;
					kabusuu = sum / a[i - 1];
					sum -= kabusuu * a[i - 1];
				}
			}
			else {
				if(a[i] < a[i - 1]) {
					katteru = false;
                  sum += kabusuu * a[i - 1];
					kabusuu = 0;
				}
			}
		}
		if(kabusuu != 0)
			sum += kabusuu * a[n];


		sc.close();
		System.out.println(sum);

	}
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
long long arr[1000000];
int main()
{
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL);   
    long long n,i,j,k,x,y,z;
    cin>>n;
    for (i=0;i<n;i++)
    {
    	cin>>arr[i];
	}
	x=arr[0];//max
	y=arr[0];//min
	z=1000;
	for (i=0;i<n;i++)
	{
		if (arr[i]>y)
		{
			z=(z/y)*arr[i]+z%y;
			y=arr[i];
		}
		else if (arr[i]<y)
		{
			y=arr[i];
		}
	}
	cout<<z<<endl;
}
//  [cpp]
#include <iostream>
#include <vector>

using lint = long long;

void solve() {
    int n;
    std::cin >> n;

    std::vector<lint> xs(n);
    for (auto& x : xs) std::cin >> x;

    lint ans = 1000;
    for (int i = 0; i + 1 < n; ++i) {
        if (xs[i] >= xs[i + 1]) continue;
        lint got = ans / xs[i];
        ans += got * (xs[i + 1] - xs[i]);
    }

    std::cout << ans << "\n";
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    solve();

    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

#define int             long long int
#define ff              first
#define ss              second
#define pb              push_back

#define vi              vector <int>
#define pii             pair <int, int>

#define loop(i,s,e)     for(int i=s;i<e;i++)
#define rloop(i,e,s)    for(int i=e;i>=s;i--)
#define mset(a,f)       memset(a,f,sizeof(a))

#define endl            "\n"
#define sz(x)           ((int) x.size())
#define all(p)          p.begin(), p.end()

#define bug(...)        __f (#__VA_ARGS__, __VA_ARGS__)
#define print(a)        for (auto x : a) cout << x << " "; cout << endl
#define Print(a,x,y)    for (int i=x; i<y; i++) cout<< a[i]<< " "; cout << endl



template <typename Arg1>
void __f (const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << endl; }
template <typename Arg1, typename... Args>
void __f (const char* names, Arg1&& arg1, Args&&... args)
{
	const char* comma = strchr (names + 1, ',');
	cout.write (names, comma - names) << " : " << arg1 << " | "; __f (comma + 1, args...);
}

const int N = 200005;

void solve()
{
	int n;
	cin >> n;
	int a[n];
	loop(i, 0, n) cin >> a[i];

	bool f = 0;
	int i = 0, m = 1000, s = 0;

	int x = 0;

	while (i < n)
	{
		if (f)
		{
			while (i < n - 1 and a[i + 1] >= a[i]) i++;
			m += (s * a[i]);
			s = 0;
			f = 0;
		}
		else
		{
			while (i < n + 1 and a[i + 1] <= a[i]) i++;
			s = (m / a[i]);
			x = s * a[i];
			m -= x;
			f = 1;
		}
		i++;

	}
	if (f) m += x;

	cout << m << endl;

	return;

}

int32_t main()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

#ifndef ONLINE_JUDGE
	freopen("input.txt",  "r",  stdin);
	freopen("output.txt", "w", stdout);
#endif

	int t = 1;
	//cin >> t;
	while (t--) solve();

	return 0;
}
//  [cpp]
// m-solutions2020_d
#include <bits/stdc++.h>
#ifdef LOCAL
#include "../cxx-prettyprint/prettyprint.hpp"
#endif
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define REP(i, n) for (int (i) = 0 ; (i) < (int)(n) ; ++(i))
#define REPN(i, m, n) for (int (i) = m ; (i) < (int)(n) ; ++(i))
#define REP_REV(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i))
#define REPN_REV(i, m, n) for (int (i) = (int)(n) - 1 ; (i) >= m ; --(i))
#define ALL(x) x.begin(), x.end()

#define INF (ll)(1e9)
#define MOD (1000000007)

#define print2D(h, w, arr) REP(i, h) { REP(j, w) cout << arr[i][j] << " "; cout << endl; }
#define print_line(vec, n) {for(int i=0;i<(n-1);i++) cout << (vec)[i] << " "; cout << (vec)[(n)-1] << endl;}
template<class T> void print(const T& x){cout << x << endl;}
template<class T, class... A> void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); }
struct PreMain {PreMain(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(20);}} premain;

int main() {
#ifdef LOCAL
    ifstream in("../arg.txt"); cin.rdbuf(in.rdbuf());
#endif

    int N;
    cin >> N;
    vector<int> A(N);
    REP(i, N) cin >> A[i];

    set<P> st;
    st.emplace(1000ll, 0ll);

    REP(i, N){

        set<P> new_st;
        for (auto e: st){
            ll m = e.first;
            ll s = e.second;
            new_st.emplace(m + s * A[i], 0);
            new_st.emplace(m % A[i], s + m / A[i]);
            new_st.emplace(m, s);
        }
        st.clear();

        for (auto e: new_st){
            bool need = true;
            for (auto f: new_st){
                if (e.first < f.first and e.second < f.second){
                    need = false;
                    break;
                }
            }
            if (need){
                st.emplace(e);
            }
        }

    }

    ll ans = 1000;
    for (auto e: st){
        ans = max(ans, e.first);
    }
    print(ans);


    return 0;
}
//  [cpp]
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <cstdint>
#include <cmath>
#include <bitset>
#include <string>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <random>
#include <chrono>

#define N_TIMES(i, n)     for ( uint64_t i = 0;     i <  n; ++i )
#define N_TIMES_REV(i, n) for (  int64_t i = n - 1; i >= 0; --i )

template<typename T> using maximum_heap = std::priority_queue<T, std::vector<T>, std::less<T>>;
template<typename T> using minimum_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;

template<typename T>
std::istream& operator>>(std::istream &is, std::vector<T> &v)
{
  for (typename std::vector<T>::size_type i = 0; i < v.size(); ++i) {
    is >> v[i];
  }
  return is;
}

using namespace std;

struct DPItem
{
  uint64_t money, stock, price;
  DPItem(uint64_t money, uint64_t stock, uint64_t price)
    : money(money), stock(stock), price(price) {}
  uint64_t operator()() const {
    return money + stock * price;
  }
  bool operator<(const DPItem &rhs) const {
    return (*this)() < rhs();
  }
  bool operator>(const DPItem &rhs) const {
    return (*this)() > rhs();
  }
};

const uint64_t M = 1e+5;

int main()
{
  uint64_t N;
  cin >> N;

  vector<uint64_t> A(N);
  cin >> A;

  vector<maximum_heap<DPItem>> dp(N + 1);
  dp[0].emplace(1000, 0, 0);
  N_TIMES(n, N) {
    uint64_t cnt = 0;
    while (!dp[n].empty() && cnt < M) {
      DPItem item = dp[n].top(); dp[n].pop();
      // 何もしない
      dp[n + 1].push(item);
      ++cnt;

      // 全株売却
      if (item.stock > 0 && item.price < A[n]) {
        if ((n == N - 1) || (n < N - 1 && A[n] > A[n + 1])) {
          dp[n + 1].emplace(item.money + item.stock * A[n], 0, 0);
          ++cnt;
        }
      }

      // 最大購入
      uint64_t c = item.money / A[n];
      if (item.stock == 0 && c > 0) {
        if ((n == N - 1) || (n < N - 1 && A[n] < A[n + 1])) {
          dp[n + 1].emplace(item.money % A[n], item.stock + c, A[n]);
          ++cnt;
        }
      }
    }
  }

  uint64_t max_money = 0;
  while (!dp[N].empty()) {
    DPItem item = dp[N].top(); dp[N].pop();
    max_money = max(max_money, item());
  }
  cout << max_money << endl;

  return 0;
}
//  [cpp]
// D.

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <set>
#include <map>
#include <bitset>

using namespace std;

typedef long long LL;
typedef pair<LL, LL> LLLL;
typedef pair<LLLL, LLLL> LLLLLLLL;

int main(int argc, char* argv[]) {
#ifdef _MSC_VER
	while (true)
#endif
	{
		LL n = -1;
		cin >> n;
		if (n < 0) return 0;
		vector<LL> a(n), b;
		for (int i = 0; i < n; ++i) {
			cin >> a[i];
		}
		b.push_back(a[0]);
		for (int i = 1; i < n; ++i) {
			if (b.back() != a[i]) {
				if (b.size() >= 2 && b[b.size() - 2] > b.back() && b.back() > a[i]) {
					b.pop_back();
				}
				b.emplace_back(a[i]);
			}
		}
		a = b;
		n = a.size();
		a.push_back(a.back());
		a.push_back(a.back());

		vector<LLLLLLLL> q;
		q.emplace_back(LLLLLLLL(LLLL(1000, 1000), LLLL(0, 0)));
		for (int i = 0; i < n; ++i) {
			if (a[i] == a[i + 1]) continue;
			if (a[i] > a[i + 1] && a[i + 1] > a[i + 2]) continue;
			vector<LLLLLLLL> nq;
			if (a[i] < a[i + 1]) {
				for (auto kv : q) {
					LL m = kv.first.second;
					if (m < a[i]) {
						nq.emplace_back(kv);
					} else {
						LL x = m / a[i];
						LL s = kv.second.first + x;
						m -= a[i] * x;
						nq.emplace_back(LLLLLLLL(LLLL(s * a[i + 1] + m, m), LLLL(s, 0)));
						if (x > 1) {
							--s;
							m += a[i];
							nq.emplace_back(LLLLLLLL(LLLL(s * a[i + 1] + m, m), LLLL(s, 0)));
						}
					}
				}
			} else {
				for (auto kv : q) {
					LL m = kv.first.second + kv.second.first * a[i];
					nq.emplace_back(LLLLLLLL(LLLL(m, m), LLLL(0, 0)));
				}
			}
			sort(nq.begin(), nq.end());
			nq.resize(unique(nq.begin(), nq.end()) - nq.begin());
			sort(nq.rbegin(), nq.rend());
			if (nq.size() > 100000) {
				nq.resize(100000);
			}
			q = nq;
		}
		LL ans = 0;
		for (auto kv : q) {
			LL m = kv.first.second + kv.second.first * a[n - 1];
			ans = max(ans, m);
		}
		cout << ans << endl;
	}
	return 0;
}
//  [c]
#include <stdio.h>

#define ll long long

int main(int argc, char *argv[]) {
	int N;
	scanf("%d", &N);
	int A[81];
	for (int i = 0; i < N; i++) {
		scanf("%d", &A[i]);
	}
	A[N] = 100;

	ll money = 1000;
	for (int i = 0; i < N; i++) {
		if (A[i] < A[i + 1]) {
			ll stock = money / A[i];
			money += (A[i + 1] - A[i]) * stock;
		}
	}

	printf("%lld\n", money);
	return 0;
}
//  [c]
#include<stdio.h>

int main(void){
  int n,i;
  long long int shoji=1000,kabu=0;
  scanf("%d",&n);
  int a[n];
  for(i=0;i<n;i++){
    scanf("%d",&a[i]);
  }
  for(i=0;i<n-1;i++){
    if(a[i]<a[i+1]){
      kabu = shoji/a[i];
      shoji = shoji - kabu*a[i];
      shoji = shoji + kabu*a[i+1];
      kabu = 0;
    }
  }
  printf("%lld",shoji);
  return 0;
}
//  [c]
#include <stdio.h>

int main(void) {

  long n;
  scanf("%ld", &n);
  long a[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
  }
  long stock = 0, money = 1000;
  int flag = 0;
  for (long i = 0; i < n; i++) {
    if (flag == 0) {
      if (i != n-1 && a[i] < a[i+1]) {
        stock += money/a[i];
        money %= a[i];
        flag = 1;
      }
    } else {
      if (i == n-1 || (i != n-1 && a[i] > a[i+1])) {
        money += stock*a[i];
        stock = 0;
        flag = 0;
      }
    }
  }
  printf("%ld\n", money);

  return 0;
}
//  [c]
#include<stdio.h>
int main(){
    int n;
    scanf("%d",&n);
    long long a[n + 1];
    for(int i = 1; i <= n; i++)
        scanf("%lld",&a[i]);
    long long ans = 1000;
    for(int i = 1; i <= n - 1; i++){
        long long s = 0;
        if(a[i] < a[i + 1])
            s = ans / a[i];
        ans += (a[i + 1] - a[i]) * s;
    }
    printf("%lld\n",ans);
    return 0;
}
//  [c]
//D - Road to Millionaire /
//Hiia
#include <stdio.h>
typedef long long ll;
int main(){
  ll n;
  scanf("%lld", &n);

  ll a[200010]={};
  for(ll i = 1; i <= n; i++){
    scanf("%lld", &a[i]);
  }

  ll money=1000,tmp;
  for(ll i = 1; i <= n-1; i++){
    if(a[i]<a[i+1]){
      tmp=money/a[i];
      money=money%a[i] + tmp*a[i+1];
    }
  }

  printf("%lld\n", money);

  return 0;
}
//  [javascript]
console.log((args=>{
  const [[N],A] = args.trim().split`\n`.map(r=>r.split` `.map(v=>v|0));
  let t = 0, c = 1000, s = 0, max = 1000;
  for ( let i = 1; i < N; i++ ) {
    t = A[i] - A[i-1];
    if ( t > 0 ) {
      s += Math.floor( c / A[i-1] );
      c = c % A[i-1];
    } else if ( t < 0 ) {
      c += s * A[i-1];
      s = 0;
      if ( max < c ) max = c;
    }
  }
  return Math.max(max,c+s*A[N-1]);
})(require('fs').readFileSync('/dev/stdin', 'utf8')));
//  [javascript]
function Main(input) {
	input = input.trim().split("\n").map(function(x) { return x.split(" ")});
	let N = parseInt(input[0][0], 10);
	let v_A = input[1].map(e => parseInt(e, 10));
	let i = 0;
	while (v_A[i] != null){
		if (v_A[i] === v_A[i + 1]) {
			v_A.splice(i + 1, 1);
		} else {
			i ++;
		}
	}
	let upDown = 0;
	let tmpKabu;
	let tmpMoney = 1000;
	// console.log(v_A);
	for (let j = 0; j < v_A.length - 1; j++){
		// console.log("ud", upDown);
		if (v_A[j] < v_A[j + 1]) {
			if (upDown === 0){
				//buy at j
				tmpKabu = Math.floor(tmpMoney / v_A[j]);
				tmpMoney %= v_A[j];
				// console.log(tmpMoney, tmpKabu);
			}
			upDown = 1;
		} else {
			if (upDown === 1){
				//sell at j
				tmpMoney += tmpKabu * v_A[j];
				tmpKabu = 0;
				// console.log(tmpMoney, tmpKabu);
			}
			upDown = 0;
		}			
	}
	if (upDown === 1) tmpMoney += tmpKabu * v_A[v_A.length - 1]; //sell

	console.log(tmpMoney);
}


Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
/*! path: /home/ts3min/work/tspro/src/contest/atcoder/msol2020/d.ts */!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";(function(e){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.main=void 0;const o=r(n(2)),i=n(3);function u(e){const t=i.getNextInt(e),n=t(),r=[];for(let e=0;e<n;e++)r[e]=BigInt(t());console.log(function({N:e,A:t}){let n=BigInt(1e3);for(let r=1;r<e;r++)if(t[r-1]<t[r]){n+=n/t[r-1]*(t[r]-t[r-1])}return n}({N:n,A:r}).toString())}if(t.main=u,n.c[n.s]===e){u(o.default.readFileSync("/dev/stdin","utf8"))}}).call(this,n(1)(e))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t){e.exports=require("fs")},function(e,t,n){"use strict";function*r(e){const t=e.split(/\s+/);for(const e of t)yield e}Object.defineProperty(t,"__esModule",{value:!0}),t.getNextBigInt=t.getNextInt=t.getNext=t.getIteratorWithParser=t.getIterator=void 0,t.getIterator=r,t.getIteratorWithParser=function*(e,t){const n=e.split(/\s+/);for(const e of n)yield t(e)},t.getNext=function(e){const t=r(e);return()=>t.next().value},t.getNextInt=function(e){const t=r(e);return()=>parseInt(t.next().value)},t.getNextBigInt=function(e){const t=r(e);return()=>BigInt(t.next().value)}}]);
//# sourceMappingURL=submit.js.map
//  [javascript]
var GET = (function () {function f(s) {return new g(s);}function g(s) {this._s = s.trim().split("\n");}g.prototype.getValue = function (n) {return this._s[n];};g.prototype.getArray = function (n) {return this.stoa(this._s[n]);};g.prototype.slice = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stox(v));};g.prototype.sliceArray = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stoa(v));};g.prototype.stoa = function (s) {return s.split(" ").map(v => this.stox(v));};g.prototype.stox = function (v) {var i = +v;return (i === i) ? i : v;};return f;})();
var o = GET(require("fs").readFileSync("/dev/stdin", "utf8"));

console.log(main());
function main(){
    var N = o.getValue(0);
    var An = o.getArray(1);

    var last = 0;
    for(var j = N - 1; j > 0; j--) {
        if (An[j] > An[j - 1]) {
            last = j
            break;
        }
    }

    var result = 1000;
    var num = 0;
    for(var i = 0; N > i; i++) {
        if (last === i || An[i] > An[i + 1] && num > 0) {
            result += An[i] * num;
            num = 0;
            if (last === i) break;
        }

        if (An[i] < An[i + 1] && result >= An[i]) {
            var temp = result % An[i];
            num = (result - temp) / An[i]
            result = temp
        }
    }

    return result;
}
//  [javascript]
const input = require("fs").readFileSync("/dev/stdin", "utf8")

;(input => {

    const lines = input.split('\n')
    let N = lines[0] - 0
    const A = lines[1].split(' ').map(Number)

    let h = 0
    let m = 1000

    for (let i = 0; i < N - 1; i++) {
        if (A[i] < A[i + 1]) {
            const n = Math.floor(m / A[i])
            h += n
            m -= A[i] * n
        } else if (A[i] > A[i + 1]) {
            m += A[i] * h
            h = 0
        }
    }

    m += A[N -1] * h

    console.log(m)

})(input)
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg[1].split(" ").map(n=>parseInt(n));
    
    let profit = 0;
    let money = 1000;
    
    for (let i = 0; i<N; i++) {
        const possibleProfit = A[i + 1] - A[i];
        profit = Math.max(profit + possibleProfit, profit);
        
        // console.log("possibleProfit:" + possibleProfit)
        
        if(possibleProfit > 0) {
            let cnt = Math.floor(money / A[i]);
            money += (possibleProfit * cnt);
        }
    }
    
    console.log(money);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

func main() {
	io := NewIo(os.Stdin, os.Stdout)
	defer io.Flush()
	n := io.NextInt()
	a := io.NextInts(n)
	x := 1000
	for i := 0; i < n-1; i++ {
		if a[i+1] > a[i] {
			k := x / a[i]
			x %= a[i]
			x += k * a[i+1]
		}
	}
	io.Println(x)
}

// Io is I/O object
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo returns a new Io instance
func NewIo(r io.Reader, w io.Writer) *Io {
	return &Io{
		reader: bufio.NewReader(r),
		writer: bufio.NewWriter(w),
	}
}

// Flush flushes writer
func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

// NextLine scans a line from stdin
func (io *Io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// Next return a word from stdin
func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

// NextInt returns an integer from stdin
func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

// NextInts returns n integers from stdin
func (io *Io) NextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = io.NextInt()
	}
	return ret
}

// Println is a wrapper of fmt.Fprintln
func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	a := make([]int, n)
	var slim []int
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
		if i > 0 {
			if a[i] != a[i-1] {
				slim = append(slim, a[i])
			}
			continue
		}
		slim = append(slim, a[i])
	}
	slim = append(slim, 0)

	kabu := 0
	cash := 1000

	for i := 0; i < len(slim)-1; i++ {
		// if i == len(slim) - 1 {
		// 	if slim[i] > slim[i-1] {
		// 		cash += slim[i] * kabu
		// 		continue
		// 	}
		// 	cash += slim[i-1] * kabu
		// 	continue
		// }
		if slim[i] > slim[i+1] {
			if kabu > 0 {
				// 売る
				cash += slim[i] * kabu
				kabu = 0
			}
		} else {
			if kabu == 0 {
				// 買う
				kabu = cash / slim[i]
				cash = cash % slim[i]
			}
		}
	}
	fmt.Println(cash)

}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	as := make([]int, n)
	for i := range as {
		fmt.Scan(&as[i])
	}
	var bs []int
	for i, a := range as {
		if i == 0 {
			bs = append(bs, a)
			continue
		}
		if a == bs[len(bs)-1] {
			continue
		}
		bs = append(bs, a)
	}

	money := 1000
	stock := 0

	for i := 0; i < len(bs)-1; i++ {
		b := bs[i]
		next := bs[i+1]
		if b < next {
			// buy
			ds := money / b
			stock += ds
			money -= ds * b
		} else {
			// sell
			money += stock * b
			stock = 0
		}
	}
	if stock > 0 {
		money += stock * bs[len(bs)-1]
		stock = 0
	}
	fmt.Println(money)

}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	a := make([]int, n+1)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}


	kabu := 0
	cash := 1000

	for i := 0; i < n; i++ {
		if a[i] > a[i+1] {
			if kabu > 0 {
				// 売る
				cash += a[i] * kabu
				kabu = 0
			}
		} else {
			if kabu == 0 {
				// 買う
				kabu = cash / a[i]
				cash = cash % a[i]
			}
		}
	}
	fmt.Println(cash)

}
//  [ruby]
n = gets.chomp.to_i
a = gets.chomp.split(' ').map(&:to_i)
up_trend = a[0] < a[1]
array = []
array << a[0] if (up_trend)

for i in 1...a.size do
  if (up_trend)
    if (a[i] < a[i-1])
      array << a[i-1]
      up_trend = false
    end
  else
    if (a[i] > a[i-1])
      array << a[i-1]
      up_trend = true
    end
  end
end

if (array[-1] && array[-1] < a[-1])
  array << a[-1]
end

okane = 1000
kabu = 0
buy = true
array.each do |price|
  if (buy)
    kazu = okane / price
    kabu += kazu
    okane -= price * kazu
    buy = !buy
  else
    okane += kabu * price
    kabu = 0
    buy = !buy
  end
end
puts okane
//  [ruby]
n = gets.to_i
a = gets.split.map(&:to_i)
dp = Array.new(n + 1)
dp[0] = 1000
a << 0

1.upto(n) do |i|
  0.upto(i - 1).each do |j|
    dp[i] = [dp[j] / a[j] * a[i] + dp[j] % a[j], dp[j]].max
  end
end

puts dp[n]
//  [ruby]
n = gets.to_i
a = gets.chomp.split
n.times do |i|
    a[i] = a[i].to_i
end

money = 1000
stock = 0
(n - 1).times do |i|
    if a[i] < a[i + 1]
        tmp = money
        money %= a[i]
        stock += tmp / a[i]
        # while money >= a[i]
        #     money -= a[i]
        #     stock += 1
        # end
    else
        money += stock * a[i]
        stock = 0
        # while stock > 0
        #     money += a[i]
        #     stock -= 1
        # end
    end
end

if stock > 0
    money += stock * a.last
    stock = 0
end

puts money
//  [ruby]
require 'pp'

n = gets.to_i
a_n = gets.split.map(&:to_i)

money = 1000
kabu = 0
# 次のほうが高ければ次に売れば損はしない
# 次のほうが安ければ次で買えば損はしない
n.times do |i|
    #pp "===="
    #pp i
    #pp money
    #pp kabu

    if i == n - 1
        # 最後は全部売る
        money += kabu * a_n[i]
        kabu = 0
        break
    end

    if a_n[i+1] > a_n[i]
        # 買い
        buy = money / a_n[i]
        kabu += buy
        money -= buy * a_n[i]
    else
        # 売れるだけ売る
        money += kabu * a_n[i]
        kabu = 0
    end
end

puts money
//  [ruby]
require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)

money = 1000
cur = INF
a.each do |yen|
  if cur >= yen
    cur = yen
  else
    suu = (money / cur)
    money = money + suu * (yen - cur)
    cur = yen
  end
  # p [yen, money]
end

puts money
//  [ruby]
n = $stdin.gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
mon = 1000;kab = 0

(n-1).times do |k|
  if arr[k] < arr[k+1] && kab == 0
    kab += mon / arr[k]
    mon -= arr[k] * kab
  end
  if arr[k] > arr[k+1]
    mon += arr[k] * kab
    kab = 0
  end
end

if kab != 0
  mon += arr[n-1] * kab
  kab = 0
end
puts mon
//  [rust]
fn main() {
    proconio::input! {
        n: usize,
        a: [u64; n],
    }

    let mut r = 1000u64;
    for i in 0..n - 1{
        if a[i] < a[i + 1] {
            r += (r / a[i]) * (a[i + 1] - a[i]);
        }
    }
    println!("{}", r);
}
//  [rust]
fn main() {
    proconio::input! {
        n: usize,
        a_s: [usize; n],
    }
    let mut money = 1000usize;
    let mut stock = 0usize;
    for w in a_s.windows(2) {
        match (stock, w[0].cmp(&w[1])) {
            (0, std::cmp::Ordering::Less) => {
                stock += money / w[0];
                money -= stock * w[0];
            }
            (0, std::cmp::Ordering::Equal) => {}
            (0, std::cmp::Ordering::Greater) => {}
            (_, std::cmp::Ordering::Less) => {}
            (_, std::cmp::Ordering::Equal) => {}
            (_, std::cmp::Ordering::Greater) => {
                money += stock * w[0];
                stock = 0;
            }
        }
    }
    money += stock * a_s.last().unwrap();
    println!("{}", money);
}
//  [rust]
use proconio::input;
use proconio::marker::{Chars, Usize1};
use std::iter::Iterator;
use std::collections::*;
use std::cmp::*;
use itertools::Itertools;

#[allow(unused_macros)]
macro_rules! max {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      max($x,max!($($xs)+))
    };
  }
  
  #[allow(unused_macros)]
  macro_rules! min {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      min($x,min!($($xs)+))
    };
  }

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    input! {
    n: usize,
    mut a: [i64; n],
    }

    let mut dp = vec![0;n+1];
    dp[0] = 1000;

    for i in 0..n-1 {
      if a[i] < a[i+1]{
        let cnt = dp[i] / a[i];
        let amari = dp[i] % a[i];
        dp[i + 1] =  a[i + 1] * cnt + amari; 
      }else{
        dp[i+1] = dp[i];
      }
      
      debug!(dp);
    }
     println!("{}", dp[n-1]);
}
//  [swift]
fileprivate struct Scanner {
    private var elements = [String]()
    private var index = 0
    
    mutating func peek() -> String {
        while elements.count == index {
            elements = readLine()!.split(separator: " ").map(String.init)
            index = 0
        }
        return elements[index]
    }
    
    mutating func next() -> String {
        let value = peek()
        index += 1
        return value
    }
    
    mutating func nextInt() -> Int {
        return Int(next())!
    }
    
    mutating func nextDouble() -> Double {
        return Double(next())!
    }
}

func main() {
    var scanner = Scanner()
    let N = scanner.nextInt()
    let A = (0 ..< N).map { _ in scanner.nextInt() }
    
    var dp = [Int](repeating: Int.min, count: N + 1)
    dp[0] = 1000
    for i in 0 ..< N {
        for j in i + 1 ..< N {
            dp[j] = max(dp[j], dp[i] % A[i] + dp[i] / A[i] * A[j])
        }
        dp[i + 1] = max(dp[i + 1], dp[i])
    }
    print(dp[N])
}

main()
//  [swift]
let n = Int(readLine()!)!
 
let a = readLine()!.split(separator: " ").map { Int($0)! }
 
var stocks = 0
var money = 1000
 
for i in 1..<n {
  if a[i-1] < a[i] {
    // buy
    stocks += money / a[i-1]
    money = money % a[i-1]
  } else if a[i-1] > a[i] {
    //sell
    money += stocks * a[i - 1]
    stocks = 0
  }
}

money += stocks * a[n - 1]
 
print(money)
//  [swift]
let n = Int(readLine()!)!
 
let a = readLine()!.split(separator: " ").map { Int($0)! }
 
var stocks = 0
var money = 1000
 
for i in 0..<n-1 {
  if a[i] < a[i + 1] {
    // buy
    stocks += money / a[i]
    money = money % a[i]
  } else if a[i] > a[i + 1] {
    //sell
    money += stocks * a[i]
    stocks = 0
  }
}

//sell
money += stocks * a[n-1]
 
print(money)
//  [swift]
import Foundation

func solve(_ arr: [Int], _ m: Int) -> Int {
    var dp = [[Int]](repeating:[Int](repeating: 0, count: 3), count: arr.count) //stock, remainder, money
    dp[0] = [m/arr[0], m%arr[0], m]
    for i in stride(from: 1, to: arr.count, by: 1) {
        let ifBoughtStockPreviousDay = arr[i] * dp[i-1][0] + dp[i-1][1]
        let moneyTillPreviousDay = dp[i-1][2]
        if ifBoughtStockPreviousDay >= moneyTillPreviousDay {
            dp[i] = [dp[i-1][0], dp[i-1][1], arr[i] * dp[i-1][0] + dp[i-1][1]]
        } else {
            let m = dp[i-1][2]
            dp[i] = [m/arr[i], m%arr[i], m]
        }
    }
    return dp.last![2]
}


let n = Int(readLine()!)!
let arr = readLine()!.split(separator: " ").map { Int($0)! }

print(solve(arr, 1000))
//  [swift]
import Foundation

let n = Int(readLine()!)!
let prices = readLine()!
    .split(separator: " ")
    .map { Int($0)! }
var money = 1000
var stocks = 0

for i in 0 ..< n - 1 {
    if prices[i] > prices[i + 1] {
        // Sell
        money += stocks * prices[i]
        stocks = 0
    } else if prices[i] < prices[i + 1] {
        // Buy
        stocks += money / prices[i]
        money = money % prices[i]
    }
}

money += stocks * prices[n - 1]

print(money)
//  [swift]
func readIntList() -> [Int] {
    return readLine()!.split(separator: " ").map{Int($0)!}
}

func readInt() -> Int {
    return Int(readLine()!)!
}
func main() {
    let n = readInt()
    let aList = readIntList()
    var baget = 1000
    var stock = 0
    for i in 1...n {
        let nextPrice = aList[i+1-1]
        let nowPrice = aList[i-1]
        if stock > 0 {
            if  nextPrice >= nowPrice {
                continue
            } else {
                // sell
                baget += stock * nowPrice
                stock = 0
            }
        } else { // stock == 0
            if nextPrice <= nowPrice {
                continue
            } else {
                // buy
                stock = baget / nowPrice
                baget -= stock * nowPrice
            }
        }
    }
    if stock > 0 {
        baget += stock * aList[n-1]
    }
    print(baget)
}

main()
//  [typescript]
import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8');
//const input = fs.readFileSync('./input.txt', 'utf8');

_d(input);

function _d(input: string) {
  const [N, _A] = input.split('\n');
  const A = _A.split(' ').map((s) => parseInt(s));

  let money = 1000n; // 所持金
  let stock = 0n; // 株式

  // 明日が今日より良ければ全部買う
  // 同じなら何もしない
  // そうでなければ全部売る

  for (let index = 0; index < A.length - 1; index++) {
    const today = BigInt(A[index]);

    if (A[index] < A[index + 1]) {
      // 値上がりするので全部買う
      const trade = money / today;
      money -= trade * today;
      stock += trade;
    } else if (A[index] > A[index + 1]) {
      // 値下がりするので全部売る
      money += stock * today;
      stock = 0n;
    } else {
      // 何もしない
    }
  }

  // 残っている株式を売却
  money += stock * BigInt(A[A.length - 1]);

  console.log(money.toString());
}
//  [python]
import numpy as np

N = int(input())
a = np.array([int(i) for i in input().split()])

b = np.abs(a.reshape(N,1) - a)
print(b.max())
//  [python]
import numpy as np

N = int(input())
A = [int(i) for i in input().split()]

a = np.array(A)

b = np.sort(a)

ans = abs((b[0]) - (b[-1]))

print(ans)
//  [python]
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))
print(A.max() - A.min())