open System
open System.Collections.Generic

module InputUtility =
    let InputTokens = new Queue<string>()

    let EnsureInput () =
        if InputTokens.Count = 0 then
            let input = Console.ReadLine ()
            let s = input.Split ([|' '|], StringSplitOptions.RemoveEmptyEntries)
            if s.Length > 0 then
                for x in s do InputTokens.Enqueue(x)
                true
            else false
        else true

    let rec ReadNext () =
        if EnsureInput () then InputTokens.Dequeue ()
        else ReadNext ()

    let ReadNextInt () = ReadNext () |> int

    let Read2Int () = ReadNextInt (), ReadNextInt ()

    let ReadListOf f n =
        let rec loop acc = function
            | 0 -> List.rev acc
            | c -> loop ((ReadNext () |> f) :: acc) (c-1)
        loop [] n

    let MultipleCaseWithId f =
        let caseNum = ReadNextInt ()
        let rec loop index =
            if index = caseNum then ()
            else
                f index
                loop (index + 1)
        loop 0

    let MultipleCase f = MultipleCaseWithId (fun _ -> f ())

    let ReadList n =
        let rec loop acc = function
            | 0 -> List.rev acc
            | c -> loop (ReadNext () :: acc) (c-1)
        loop [] n

open InputUtility

module ARC075 =
    let private Bugged () = 
        let n = ReadNextInt ()
        let rec cal i (f: _ array) (g: _ array) =
            if i = n then
                f |> Seq.skip 1 |> Seq.max
            else
                [0..9] |> Seq.iter (fun i -> g.[i] <- f.[i])
                let d = ReadNextInt ()
                for i in [0..9] do
                    if f.[i] > -1 then
                        let j = (i + d) % 10
                        g.[j] <- max g.[j] (f.[i] + d)
                cal (i + 1) g f
        let na () = Array.create 10 -1
        let f = na ()
        f.[0] <- 0
        cal 0 f (na ())
        |> max 0
        |> printfn "%d"

    let Entry = Bugged

ARC075.Entry ()