


fun upperBound(array: IntArray, target: Int): Int {
    var left = 0
    var right = array.size
    while(left < right) {
        val mid = (left + right) / 2
        if (array[mid] <= target) left = mid + 1
        else right = mid
    }
    return right
}

fun main(args: Array<String>?): Unit {
    val n = readLine()!!.toInt()
    val nums = readLine()!!.trim().split(' ').map(String::toInt)
    val memo = IntArray(n + 1){-1}
    memo[memo.lastIndex] = Int.MAX_VALUE
    val sum = LongArray(n + 1){-1}
    sum[sum.lastIndex] = 0
    for (i in nums.asReversed()) {
        val pos = upperBound(memo, i)
        memo[pos - 1] = i
        sum[pos - 1] = sum[pos] + i
    }
    println(sum.first { it >= 0 })
}
