import           Control.Applicative
import           Control.Monad
import           Data.Array
import           Data.List

solve :: [Int] -> Int
solve as = maximum dp
  where
    dp = array (0, lns) [(i, f i) | i <- [0..lns]]

    -- 0 ~ i ??????????????§?????¨??????????????§???
    f 0 = head as
    f i = let ai = as !! i in  max ai (ai + dp ! (i - 1))

    lns = length as - 1

main :: IO ()
main = getContents >>= loop . map read . lines
  where
    loop :: [Int] -> IO ()
    loop (0:_)  = return ()
    loop (x:xs) = let (as, rs) = splitAt x xs
                  in  print (solve as) >> loop rs