Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in

    let rec loop i dis balance stock =
        if i = n then balance + stock * a.(n - 1) else
            if dis < 0 && a.(i) > a.(i - 1) then loop (i + 1)   1  (balance - balance / a.(i - 1) * a.(i - 1)) (balance / a.(i - 1)) else
            if dis > 0 && a.(i) < a.(i - 1) then loop (i + 1) (-1) (balance + stock * a.(i - 1)) 0 else
                loop (i + 1) dis balance stock
    in
    Printf.printf "%d\n" @@ 
    if a.(0) < a.(1) then loop 1 1    (1000 - 1000 / a.(0) * a.(0)) (1000 / a.(0))
                     else loop 1 (-1) 1000 0
)
