The longest increasing subsequence of the sequence A is the longest subsequence that satisfies Ai<Aj with all i<j.
output
Output the maximum value of sumBi, where B is one of the longest increasing subsequences of the sequence A. Also, output a line break at the end.
Example
Input
4
6 4 7 8
Output
21
We need to solve: Given sequence A of length N, find the maximum sum over all longest increasing subsequences (LIS). Among all subsequences that have maximum length (the length of LIS), we need to choose one that maximizes the sum of its elements.
We need to output that maximum sum.
Constraints not given, but likely N up to maybe 200,000? Usually LIS problems with DP can handle N up to 10^5 with patience sorting approach. But we also need to consider sum. The classic LIS problem can be extended to track not only length but also maximum sum for each possible length. However careful: we want among subsequences of maximum LIS length, the maximum sum. So we need to compute LIS length L, then among subsequences of length L, maximize sum.
We can approach with coordinate compression and segment tree / BIT that stores for each value (or for each ending value) the best (length, sum) pair, using lexicographic order: first maximize length, then sum. When processing elements from left to right, we need to query over values less than current A[i] to get best previous subsequence. Then extend it by current element.
Specifically, define dp[i] as best pair (len, sum) for subsequences ending at value (or at position) with value A[i]. But we can process online: for each element x = A[i], we query among all values < x to find the best (max length, then max sum) among previously computed results. Let best = (max_len, max_sum). Then new_len = best.len + 1, new_sum = best.sum + x. Then we need to update the data structure at index corresponding to x with the pair (new_len, new_sum). However, we might have multiple ways to get subsequences ending at the same value x, with possibly different lengths and sums. We only want to keep the best for that value for future queries? But careful: When we update at value x, we need to store the best (len, sum) for subsequences ending with value exactly x. However, what about subsequences with lower length but higher sum? They could be useful for future because they might lead to longer subsequences? No, for future extension, we only care about the best possible prefix to extend to a larger value. For extending to a larger value later, we want the subsequence that gives the maximum length, and in case of tie maximum sum, because that will yield the best eventual sum for a given length? Actually, suppose we have two subsequences both ending with value x, one has length 3 sum 100, another has length 4 sum 80. For extending to a future value y > x, the one with length 4 yields length 5, while the one with length 3 yields length 4. So obviously the length is more important, because it leads to longer LIS. But could there be a scenario where the length-3 subsequence yields a longer final LIS than the length-4? Not possible, because you always add one more element, so length of new subsequence = old_len+1. So the old with higher length always yields higher final length. So for future queries, we want to maximize length first, then sum. So for each value x, we should store the best pair (len, sum) among subsequences ending with exactly x, using lexicographic order (len max, then sum max). Then when we query over values < x, we need to retrieve the best pair over all stored values less than x. That can be done with segment tree that supports range query for maximum according to that order. The update at point x will set the stored value to max of current and new pair.
After processing all elements, we need to find overall best pair, but specifically among those with maximum length (the LIS length). So we can track global maximum length L_max. Then among all pairs (len, sum) we need the maximum sum for len == L_max.
We can also simply compute the maximum sum for each length? But the segment tree approach can retrieve global max at end by scanning all values, but better to keep a variable.
Thus algorithm:
Read N and array A.
Compress values if necessary (since values might be up to 1e9). We'll need to map A to ranks (sorted unique). However we need to query over values less than current A[i] (strictly). So if we compress, we need to maintain original order of values; but we need strict inequality. So if we assign ranks based on sorted order, we need to handle duplicate values? The problem says increasing subsequence requires A_i < A_j (strict). So equal values not allowed. So for duplicate values, we cannot extend from equal. So in compression we treat each distinct value as a point, but duplicates share same rank. Since we cannot extend from equal, we must ensure that when we query for values < x, we query ranks less than rank(x). So using ranks is fine.
But careful: If there are duplicate values, we may have multiple subsequences ending with same value. Our segment tree will store best for that rank; if we process elements in order, we may have updates for same rank multiple times; we need to take max. However, note that when we query for < rank(x), we consider only previous elements (positions earlier). So at the moment we process an element with value x, we have already processed all previous elements. The segment tree currently contains best pairs for values from earlier positions. That's fine. So we need to update after processing each element.
Thus we can:
let sorted unique = vals; map each value to its index (1-based).
Let M = len(vals)
Build segment tree (or BIT) of size M, each node stores best pair (len, sum) over its range. Initially all pairs (0,0) maybe? But for empty subsequence, length 0 sum 0. However, note that a subsequence can start with any element; from nothing length 0 sum 0 we can extend to length 1 sum = A[i]. So we need a base state: for query before any element, we need to get (0,0). So we can initialize the segment tree with (0,0) for all indices, or we can handle query returning (0,0) when no previous. For BIT we can implement that default.
Process i from 1 to N:
rank = idx[A[i]]
query result = best over range [1, rank-1] (since values less than current). If rank-1 <1, result = (0,0)
new_len = result.len + 1
new_sum = result.sum + A[i]
new_pair = (new_len, new_sum)
Now we need to update at position rank: if current stored pair at rank is worse than new_pair, update it.
But we also need to consider that there might be an existing pair at rank that is better (greater len or same len but greater sum) already; we should keep the best. So update = max(current, new_pair) with lex order.
However, we also need to ensure that the update propagates to segment tree range queries.
While processing, keep track of global best: after updating, if new_len > best_len, update best_len and best_sum. If new_len == best_len, best_sum = max(best_sum, new_sum).
At the end, output best_sum.
But careful: Could there be a case where the best sum for length L comes from a subsequence that doesn't use the best pair for its ending value? Our DP ensures that for each ending value, we keep the best pair to extend further. But for the final answer, we only need max sum for length L, not necessarily requiring that the pair is the best for its ending value. Since we track best_sum for each length L globally, it's fine.
Now complexity: O(N log M). With N up to 200,000, this is fine.
We need to implement segment tree or BIT that can combine pairs lexicographically.
But BIT typically stores for prefix max. Since we need query over prefix (values less than current) and update pointwise, BIT works if the operation is associative and we can take max. However BIT normally works for prefix queries when the combine is like sum, or max. But max is associative and we can combine as we go: for BIT that stores the best pair in each index, query for prefix max can be done by taking max over indices that are part of the prefix. But careful: BIT works by combining intervals that are powers of two, but max is idempotent and we can combine. However typical BIT implementation for prefix maximum works when we only update with increasing values and we can't later override with lower values? Actually BIT for prefix maximum works if we only do point updates that increase the value (or set to a larger value). Because BIT stores for each node the maximum over a range. If we update a point to a larger value, we can update all relevant nodes by taking max with the new value. But if we later update a point to a value that is lower, we would need to recalculate the node's value from the underlying points, which BIT cannot easily do. However, in our case, we are only setting each point to the best pair; we may update a point multiple times with possibly better pairs (higher length or same length higher sum). Those updates are monotonic in the sense that the pair only improves (according to lex order). So we can do BIT with monotonic updates: each update will only set the pair to a "better" one. So we can update the BIT node by comparing and setting to max if new is better. But careful: If we have an existing pair (len, sum) at that index, and we get a new pair (len', sum') that is better, we will update the BIT to reflect the new max. But is it guaranteed that the new pair is always better or equal? Yes, because we only replace with max of current and new. So the stored value at the point is non-decreasing in lex order. However, there is a nuance: Suppose we have a point that had a pair (3,100). Later we find a new pair (3,80). It's not better; we wouldn't update. So updates are only when we find a better pair. So monotonicity holds.
Thus we can use BIT for prefix max. However we need to define the combine function: given two pairs (l1, s1) and (l2, s2), we say (l1,s1) > (l2,s2) if l1 > l2, or l1 == l2 and s1 > s2. We'll maintain the maximum according to this order.
Now BIT query: for prefix up to rank-1, we iterate i from rank-1 down to 0? Actually BIT standard query for prefix max: res = (0,0) initially, while idx > 0: res = max(res, bit[idx]), idx -= idx & -idx. That works because each bit[idx] stores the maximum over range (idx - lowbit(idx) + 1, idx]. Combining them yields the maximum over prefix.
Update: when we set a point at index pos to a better value, we need to update all bit indices that cover pos: while pos <= M: bit[pos] = max(bit[pos], new_pair); pos += pos & -pos.
However, we must also store the exact value at the point? We don't need separate array because bit will store aggregated max; but when we update, we need to compare new_pair with the current best at that point. But since we only have aggregated, we cannot know the exact point value. However, for updates, we need to ensure that if new_pair is better than the current point's stored best, then we update the BIT nodes. But if new_pair is not better, we do nothing. To check whether it's better, we need to know the current best at that point. So we need an array best_at_point[pos] to keep the best pair for that exact index. We'll maintain it separately and only call BIT update when we actually improve it.
Thus:
best_point = array of pairs size M+1, init (0,0)
BIT array of pairs size M+1, init (0,0)
Process each A[i]:
r = rank of A[i] (1-indexed)
prev_best = query(r-1) // returns best pair over indices 1..r-1
new_len = prev_best.len + 1
new_sum = prev_best.sum + A[i]
new_pair = (new_len, new_sum)
// now try to update at r
if new_pair is better than best_point[r] (i.e., (new_len > best_point[r].len) or (new_len == best_point[r].len and new_sum > best_point[r].sum)):
best_point[r] = new_pair
update BIT at r with new_pair // BIT.update(r, new_pair) which sets bit nodes to max
// also track global best for length L: we can just keep best_len and best_sum
Alternatively, we could update BIT always with new_pair, but then BIT might store a pair that is not actually the point's value; but since we only use BIT for query, it's okay as long as we don't cause false positives: If we add a new_pair that is not better than the existing point's best, but still better than some BIT node's stored max? Actually BIT node stores the max over its range. If new_pair is not better than the current point's best, it's not going to be better than the current max for that range (since current best at that point is already at least as good). But it's possible that the new_pair is worse than the current point's best, but still better than some other values? However, the BIT node's max should be the true max over the range. If we update it with a value that is not actually the new point's best (but still maybe greater than current stored max for that node?), then it could incorrectly raise the max. But we only want to update if new_pair > current point's best. If it is not, then it is <= current point's best, and thus <= current max for the range, so updating would not change the max (since we would do bit[pos] = max(bit[pos], new_pair). If new_pair <= current max, then bit[pos] remains unchanged. However, if we update with new_pair that is not better than the current point's best but the BIT node's current max is lower than new_pair? That cannot happen, because current point's best contributes to that node's max, so node's max >= point's best >= new_pair. So bit[pos] would remain unchanged. So we could simply always update BIT with new_pair without checking best_point[r]. Because BIT will take the max and not increase incorrectly. But there is a subtlety: if later we get an even better pair at that point, we will update BIT again. But if we always update BIT with new_pair, we may be doing redundant updates but no harm. However, we must be careful about the scenario where there is a new_pair that is better than the current point's best, but we haven't updated best_point[r]? We would still need to know that for later comparisons? Actually, we need to know the best at the point to compare with new_pair when processing later elements with the same value? Because for later queries, the BIT will contain the best anyway. But for deciding whether to update BIT, we don't need to compare; we can always update BIT with new_pair. However, the BIT update will set bit nodes to max. But we also need to know what is the best for that point to be used when later we process another element with the same value (same rank) and we query for values less than that rank. For that, BIT query will consider the max over range 1..r-1, which does not include r itself. So it doesn't matter what's stored at r for those queries. However, when we later process an element with a larger value > x, the BIT query will include r as part of the prefix if that larger value's rank > r. So we need the best for value r to be included. If we always update BIT with new_pair, the BIT will eventually hold the best among all updates for that point, which is fine. But we also need to consider that if we update BIT with a new_pair that is not better than the previously stored best for that point, the BIT nodes already have the best, so no change. So we can avoid storing best_point entirely and just always call BIT.update(r, new_pair). The BIT will hold the max over its range, and that's sufficient.
But careful: BIT nodes store the max over a range, not necessarily the point value. When we update a point r with a value, we propagate to nodes covering r. The nodes store the max over their range. If we later update point r with a larger value, those nodes will be updated accordingly. If we later update point r with a smaller value, they will not change; but that's okay because we never need to decrease. Since our updates only ever produce non-decreasing values at point r (lexicographically), we can safely always call update. However, is it guaranteed that each update is non-decreasing? Not necessarily; we might compute new_pair that is worse than an earlier computed pair for the same r. In that case, updating BIT would do nothing because max would not increase. But we still have to ensure that we don't lose the fact that the best pair remains. Since we are not storing the best at point separately, but BIT's nodes might contain that best from the previous update. If we do nothing on a worse update, the BIT remains correct. So we can just do BIT.update(r, new_pair) each time. The update function sets bit[pos] = max(bit[pos], new_pair). So it's idempotent: it ensures bit nodes are at least as high as any value we have passed. This works if we never need to "replace" a value that is no longer valid due to some condition (which we don't). So we can skip the separate best_point array.
But wait: There is a nuance: The DP recurrence requires that we consider only subsequences that end at positions before the current element. The BIT stores best over all previously processed elements for each value, regardless of their positions? But since we process left to right, at the time we process element i, the BIT contains information from elements with index < i. When we update BIT with new_pair for the current element's value, it will be available for later elements (index > i). That's correct.
Thus, we can use BIT to store the best (len, sum) for each value from previously processed elements. For each element A[i], we query prefix rank-1 to get the best previous subsequence that can be extended. Then we compute new_pair and update BIT at rank with new_pair. Also track global answer.
Now, what about the base case: For the first element, query rank-1 returns (0,0) (if we initialized BIT with (0,0) everywhere). That yields len=1 sum=A[i]. Then we update BIT at rank with (1, A[i]) if better than existing (which initially is (0,0) so will be set). That's fine.
Thus algorithm is simple.
Now we need to handle possibly large sums; sum of up to N * max(A[i]), could be up to maybe 10^14, so need 64-bit integer (long long). Use Python's int (unbounded) but fine.
Now, we must verify correctness on example: N=4, A=[6,4,7,8]
Sorted unique = [4,6,7,8] ranks: 6->2, 4->1, 7->3, 8->4
Process:
i=1, val=6 rank=2: query prefix 1 -> (0,0) -> new (1,6). update rank2 with (1,6). global best: len=1 sum=6
i=2, val=4 rank=1: query prefix 0 -> (0,0) -> new (1,4). update rank1 with (1,4). global best: len=1 sum=6 (still)
i=3, val=7 rank=3: query prefix2 -> max over ranks1-2. rank1 has (1,4), rank2 has (1,6) => best (1,6) (since same length, higher sum). new_len=2, new_sum=13. update rank3 with (2,13). global best: len=2 sum=13
i=4, val=8 rank=4: query prefix3 -> max over ranks1-3: we have (1,4), (1,6), (2,13) => best (2,13). new_len=3, new_sum=21. update rank4 with (3,21). global best: len=3 sum=21.
Output 21. matches.
Now consider duplicate values: Suppose A=[2,2,3]. LIS length? The longest increasing subsequence is of length 2 (2,3) but careful: cannot use both 2's because need strictly increasing. So LIS length=2. We need max sum among length-2 subsequences: possibilities: (2,3) sum=5 from first 2 and 3; (2,3) from second 2 and 3 sum=5; also possibly (2,3) both? So sum=5. Let's test algorithm with compression: values [2,3] ranks: 2->1, 3->2. Process:
i=1: val=2 rank=1, query prefix0 => (0,0) -> new (1,2). update rank1 -> (1,2). best len=1 sum=2
i=2: val=2 rank=1, query prefix0 => (0,0) -> new (1,2). update rank1: compare (1,2) with existing (1,2) -> same, maybe no update but BIT.update will max with (1,2) no change. best stays len=1.
i=3: val=3 rank=2, query prefix1 -> max over rank1: (1,2). new (2,5). update rank2 -> (2,5). best len=2 sum=5. Output 5. correct.
Now consider a scenario where there is a choice: A = [1, 3, 2, 4]. LIS length = 3? Let's see: increasing subsequences: 1,3,4 length3 sum=8; 1,2,4 length3 sum=7; So max sum is 8. Let's simulate:
Sorted unique: [1,2,3,4] ranks: 1->1,3->3,2->2,4->4.
Process:
i1: val=1 rank1: query prefix0 -> (0,0) -> (1,1) update rank1 (1,1)
i2: val=3 rank3: query prefix2 -> max over ranks1-2: rank1 (1,1) rank2 (0,0) -> best (1,1) -> new (2,4) update rank3 (2,4)
i3: val=2 rank2: query prefix1 -> rank1 (1,1) -> new (2,3) update rank2 (2,3) (since (2,3) better than (0,0)?)
i4: val=4 rank4: query prefix3 -> max over ranks1-3: rank1 (1,1), rank2 (2,3), rank3 (2,4) -> best? Compare (2,3) vs (2,4): (2,4) is better (same length, higher sum) => best (2,4). new (3,8) update rank4 (3,8). global best: len=3 sum=8. correct.
Now consider scenario where two subsequences end at same value with same length but different sums; BIT holds max sum for that length. Good.
Now consider scenario where there are subsequences ending at same value with different lengths: but we always keep the best pair (max length, then max sum). So if we have a longer length, we will overwrite the previous (shorter). That is fine.
But is it possible that a shorter subsequence with a very high sum could later be extended to achieve a longer LIS than the current longest? No, because if we have a longer subsequence already ending at that value, then extending that longer one will yield even longer length. But there might be a scenario where the longer subsequence ending at value x cannot be extended to a future y due to sum? The extension condition only depends on values being increasing, not on sum. So length is the only factor for ability to extend. So storing the longest for each value is optimal for future extension. So the DP is correct.
Thus solution: BIT of pairs.
Implementation details:
We'll implement BIT where each element is a tuple (length, sum). We'll define a function better(a,b) to compare and return the better one.
BIT array: list of tuples of length M+1, initially (0,0).
query(pos): returns best over indices 1..pos. If pos==0 returns (0,0). Implementation: res = (0,0); while pos>0: res = better(res, bit[pos]); pos -= pos & -pos.
We must be careful: For BIT query, the order of combination matters? Since we are taking max, and max is commutative and associative, order doesn't matter. So fine.
Now compress: Use sorted(set(A)) and map each value to its index (1-based). Since values up to maybe 10^9, we use Python's dict.
Now we need to process in given order. That's it.
Edge cases:
N=0? Not possible, N given but maybe zero? Usually N>=1.
All elements decreasing: LIS length=1, answer = max element. Our algorithm: For each element, query prefix returns (0,0) -> new (1, A[i]) -> update at its rank. Global best will be max over these sums? Since we track best_len and best_sum, and we update when new_len > best_len or equal and sum greater. Initially best_len=0. First element sets best_len=1, best_sum=A[1]. Then for later with same len=1, if sum > best_sum we update. So final answer is max element. Works.
Negative numbers? The problem didn't specify positive; sums could be negative. However, we need to consider base case: empty subsequence sum=0, length=0. But if all numbers are negative, the maximum sum for length 1 would be the largest (least negative) number, which might be negative. That's fine. Our base (0,0) for empty subsequence is valid: sum 0 is higher than any negative sum? But wait: For a negative number, we could choose empty subsequence? But we need longest increasing subsequence, which must have length at least 1 if N>0. The longest increasing subsequence length is at least 1. So we must consider subsequences of length 1. However, if we use empty subsequence as base, we get new_len=1, new_sum = 0 + negative = negative. That's correct. There's no option to not take any element. So final answer may be negative. But is the empty subsequence considered as a valid prefix? Yes, it's the base for building any subsequence. So it's fine.
But consider if numbers are negative and we have sum zero from empty? The sum of a subsequence of length 0 is 0, which is larger than any negative sum. However, that doesn't affect the DP for positive lengths because we add the negative number to the base sum. So the DP yields correct sums.
But one nuance: When we query for prefix less than current value, we might get (0,0) if no previous subsequence can be extended. That is correct.
Now complexity: O(N log N). Works for N up to maybe 2e5.
Now we should also consider alternative approach: using patience sorting with piles and maintaining best sum for each pile. However, BIT approach is simpler.
Now let's consider implementation in Python:
def solve():
import sys
input_data = sys.stdin.read().strip().split()
if not input_data:
return
it = iter(input_data)
N = int(next(it))
A = [int(next(it)) for _ in range(N)]
code
# coordinate compression
vals = sorted(set(A))
rank = {v:i+1 for i,v in enumerate(vals)} # 1-indexed
M = len(vals)
# BIT arrays for length and sum? Could store as tuple.
# We'll implement two arrays: bit_len and bit_sum, but better to store as a pair.
bit_len = [0]*(M+1)
bit_sum = [0]*(M+1)
# comparison function
def better(i, cur_len, cur_sum):
# compare current best stored at index i (bit_len[i], bit_sum[i]) with candidate (cur_len, cur_sum)
if cur_len > bit_len[i] or (cur_len == bit_len[i] and cur_sum > bit_sum[i]):
bit_len[i] = cur_len
bit_sum[i] = cur_sum
# else no change
def update(pos, length, sum_val):
while pos <= M:
if length > bit_len[pos] or (length == bit_len[pos] and sum_val > bit_sum[pos]):
bit_len[pos] = length
bit_sum[pos] = sum_val
pos += pos & -pos
def query(pos):
best_len = 0
best_sum = 0
while pos > 0:
if bit_len[pos] > best_len or (bit_len[pos] == best_len and bit_sum[pos] > best_sum):
best_len = bit_len[pos]
best_sum = bit_sum[pos]
pos -= pos & -pos
return best_len, best_sum
best_global_len = 0
best_global_sum = 0
for x in A:
r = rank[x]
prev_len, prev_sum = query(r-1)
new_len = prev_len + 1
new_sum = prev_sum + x
# update BIT at r
update(r, new_len, new_sum)
# update global best
if new_len > best_global_len or (new_len == best_global_len and new_sum > best_global_sum):
best_global_len = new_len
best_global_sum = new_sum
# output best_global_sum
print(best_global_sum)
But is there any subtle issue? Consider that we might have a subsequence that ends with a value v, but later we find a subsequence ending with the same v that has same length but higher sum. Then update(r) will improve the BIT nodes. That's okay.
Now test with example: works.
Potential bug: The BIT query returns the best over all values <= pos. But we query prefix r-1, which excludes r. Good.
Now we must consider if there are multiple elements with same value, and we process them. For later same value, query prefix r-1 includes only values strictly less, not including previous same values, because we haven't updated BIT with the previous same value? Actually we have updated BIT for previous same value, but those updates are at rank r. Since we query prefix r-1, we don't include them. So later same value cannot extend from earlier same value because it would break strict increasing. So correct.
Now consider if values are not distinct and we need to treat "strictly less" correctly. The compression mapping ensures that equal values map to same rank. So querying up to rank-1 excludes them.
Now we need to handle large N and maybe up to 10^6? Python BIT with two separate arrays is fine. However, if we store as tuple and update using comparison, it's okay.
But note: The BIT update function uses while pos <= M: if new pair better than current bit node, update. However, we must consider that the bit node stores the max over its range. If we update with a new pair that is better than the current node's stored max, we set it to new. But if the new pair is better than the current node's max, it should become the new max. However, it's possible that the current node's max comes from some other value in that range, and the new pair is better, so we should update. That's fine.
But is there a scenario where the new pair is better than the current max of the node, but the current max of the node is from a different value, and the new pair is for a value that is within the node's range. So updating the node to the new pair is correct because it becomes the new maximum for that range.
Now, is it possible that later we get an even better pair for the same value, which might be even larger? We will update again.
Now, what about queries: when we query prefix, we combine multiple nodes that partition the prefix. Since each node stores the max over its segment, taking max of those gives the max over the whole prefix. So correct.
Thus BIT works.
Now we need to ensure we consider that the BIT nodes store aggregated max, and when we update a point, we update all covering nodes. Since updates are monotonic, it's fine.
Now test with random small arrays to ensure correctness. We'll do mental test.
A = [5, 1, 6, 2, 7, 3, 8, 4]. LIS length? The longest is 4? Actually can we get 5? Let's try: 1,2,3,4,8? But 8 is after 4? Sequence: indices: 1:5,2:1,3:6,4:2,5:7,6:3,7:8,8:4. Increasing subsequence: 1,2,3,4,8? Order: 1 at idx2, 2 at idx4, 3 at idx6, 4 at idx8, 8 at idx7? No, 8 is before 4 (idx7 vs idx8). So can't. Could do 1,2,3,8? That's length4. Or 5,6,7,8 length4. So LIS length=4. Sum max? Likely 5+6+7+8=26 vs 1+2+3+8=14 vs maybe 1+6+7+8=22? Actually 1 (idx2),6(idx3),7(idx5),8(idx7) =22. Or 5,6,7,8=26 is highest. So answer 26.
Simulate algorithm:
Values: [1,2,3,4,5,6,7,8] ranks 1..8.
Process:
i1:5 rank5 -> query prefix4: (0,0) -> (1,5) update rank5.
i2:1 rank1 -> query0: (0,0) -> (1,1) update rank1.
i3:6 rank6 -> query5: best over ranks1-5: we have rank1 (1,1), rank5 (1,5) -> best (1,5) -> new (2,11) update rank6.
i4:2 rank2 -> query1: rank1 (1,1) -> new (2,3) update rank2.
i5:7 rank7 -> query6: best over ranks1-6: rank1 (1,1), rank2 (2,3), rank5 (1,5), rank6 (2,11) -> best is (2,11) (len2 sum11) -> new (3,18) update rank7.
i6:3 rank3 -> query2: best over ranks1-2: rank1 (1,1), rank2 (2,3) -> best (2,3) -> new (3,6) update rank3.
i7:8 rank8 -> query7: best over ranks1-7: we have rank1(1,1), rank2(2,3), rank3(3,6), rank5(1,5), rank6(2,11), rank7(3,18) -> best (3,18) -> new (4,26) update rank8. Global best len4 sum26.
i8:4 rank4 -> query3: best over ranks1-3: rank1(1,1), rank2(2,3), rank3(3,6) -> best (3,6) -> new (4,10) update rank4. Global best remains 26.
Output 26. Works.
Now we need to consider that the problem might require output of the maximum sum, but we need to handle large N and maybe up to 2*10^5. BIT O(N log N) is fine.
Now, a potential pitfall: Our BIT query returns the best pair over values less than current. However, this best pair is based on length and sum among subsequences ending at any value less than current. That is correct. But is it always optimal to extend the best pair according to lex order? We argued yes because length dominates. However, consider scenario where we have two subsequences: one with length 2 sum 100, and another with length 3 sum 0. The length 3 is longer. For extending to a value larger than both, length 3 gives length 4 sum=0+x, length 2 gives length 3 sum=100+x. If we are only interested in maximum sum among LIS (which we are) we might think that maybe the final LIS length is 4, but we might want to choose a different path that yields a higher sum but also length 4? Wait, we need to find the maximum sum among subsequences of the maximum possible length L. So if the overall LIS length is L, we want the maximum sum for that length. The DP that always extends the best pair (max length, then sum) may not necessarily produce the maximum sum for length L if the path to achieve L uses a subsequence that is not the best at some intermediate step in terms of length? But if we always pick the longest prefix, we guarantee that we can reach the maximum length. However, there could be multiple ways to achieve length L. For the final length L, we want the maximum sum. At each step, when we compute new_len = prev_len+1, we need to consider all previous subsequences that can be extended. The best sum for a given length ending at a particular value might not come from the longest previous subsequence? Actually, to achieve a certain length L ending at value x, we need a previous subsequence of length L-1 ending at some value y < x. Among those, we want the one with maximum sum, because we are maximizing sum for a fixed length. So at each DP state (ending value x, length L), we want the maximum sum among subsequences of length L ending at x. That is exactly what we compute if we consider all previous subsequences. But our BIT stores for each value the best (length, sum) lexicographically (max length, then sum). That does not keep all lengths; it only keeps the best length for each value. However, for a given length L, we may need to consider previous subsequences of length L-1, even if they are not the overall best for that ending value. For example, suppose we have two subsequences ending at value y: one with length 3 sum 100, and another with length 4 sum 0. The overall best for y is (4,0) because length 4 is longer. Now consider a future value x > y. If we only keep the best (4,0) for y, then when we extend to x we get length 5 sum = 0 + x. But there might be a subsequence of length 4 from y (but length 3? Actually we need L-1 = L' maybe? Let's think: Suppose the global LIS length is 5. To achieve length 5 ending at x, we need a previous subsequence of length 4 ending at some y < x. If we only keep the best for y (which is length 4 sum 0), we get sum 0+x. However, there might be another subsequence ending at some other value z (or even same y) of length 4 with sum 100? But we only have length 3 sum 100 at y, not length 4. So that doesn't help. But could there be a case where at a value y, we have both length 3 sum 100 and length 2 sum 200? To achieve length 4 at x, we need length 3, not length 2. So we need specific lengths. The BIT that stores only the best (max length) for each value might discard a subsequence of length 3 if there exists a longer length 4, because for extending to length 4 we would need length 3? Actually, if we have length 4 at y, we can get length 5 at x. If we have length 3 at y, we can get length 4 at x. They target different final lengths. So to correctly compute the maximum sum for the LIS length L, we need to consider all possible lengths, because the LIS length might be L, and we need the best sum for that length. At each step, we want to compute the best sum for each possible length up to that point. The BIT approach storing only best per value based on length might not be sufficient, because we might lose information about lengths that are not maximal for that value but could be needed to form the maximal overall length with a better sum? Let's analyze more carefully.
The DP problem is: For each position i (or value), we want to know, for each possible length ℓ, the maximum sum of an increasing subsequence of length ℓ ending at that value. But we can compress by value because subsequences are based on values. However, we process in order of positions, but the increasing condition is on values, not positions. The classic LIS DP: dp[i] = max over j < i with A[j] < A[i] of dp[j] + 1 (length). For sum, we might want to store for each position the best sum for its length. But we want to consider all j. That's O(N^2). To optimize, we need a data structure that, for each value, can query the best (length, sum) for values less than current, but we need to consider all lengths separately, because when we extend, the new length = old length + 1, so we need to know for each possible length ℓ, the maximum sum for subsequences of length ℓ ending at a value less than current. Then we can compute for length ℓ+1 at current. So we need to maintain, for each value (or for each DP state based on value), the maximum sum for each length? That seems like a 2D problem.
But there is known technique: For LIS with maximum sum, we can use a Fenwick tree that stores for each value the best (length, sum) pair. However, I recall that for problems like "Maximum sum increasing subsequence", the standard solution is O(N log N) with BIT/segment tree storing the maximum sum for any subsequence ending with a given value, regardless of length? Actually, "Maximum sum increasing subsequence" (MSIS) is a different problem: find increasing subsequence (not necessarily longest) with maximum total sum. That can be solved with BIT storing max sum for values, updating with current value + best sum from lower values. That's a standard problem. But here we are constrained to longest length.
So we need to incorporate both length and sum. The BIT storing only the best (length, sum) lexicographically may not be sufficient because it discards lower lengths that could lead to same final length with higher sum? Let's test with a counterexample.
Consider sequence: A = [1, 100, 2, 3, 4, 5]. LIS length: There is 1,2,3,4,5 length 5. Also 100,? can't extend because after 100 only 2,3,4,5 which are less. So LIS length = 5. Now, the maximum sum among length 5 subsequences: The only one is 1,2,3,4,5 sum=15. But suppose we have a scenario where there are two ways to get length 5: one with sum 15, another maybe with sum larger? For a counterexample, we need two different paths to achieve length 5, where one path uses a high value early that prevents later high values? But LIS requires strictly increasing, so you cannot have both a very high value early and still have many increasing values after if they are smaller. However, maybe there is a case where the longest length is L, and there are multiple subsequences of that length, but some may have better sums if they use larger numbers even if they skip some smaller numbers. The key is whether storing only the best length for each value can cause us to miss a subsequence of length L-1 that has a higher sum but lower length? Actually, to achieve length L, we need a previous subsequence of length L-1. If for some value y we have both length L-1 and length L (longer). But if the length L is longer, it cannot be used to achieve final length L because we would need length L-1. But could we have a scenario where to achieve final length L, we need to use a subsequence that ends at some value y with length L-1, but there is also a longer subsequence (length L) ending at that same y, which we store as best, overwriting the length L-1. Then when we later try to compute for a value x > y, we would only have length L (best) and would compute length L+1, not length L. So we lose the ability to compute length L ending at x using the length L-1 from y. However, there might be another value z with length L-1 that we can use. But if the highest sum length L-1 was at y, and it's overwritten, we may lose the best sum for length L at x. So we need to keep, for each value, the best sum for each length? But that would be too many.
But is it possible that the best sum for length L (overall) requires using a subsequence of length L-1 that is not the best for its ending value? Yes, consider:
Let A = [2, 1, 3, 4]. The LIS length is 3 (1,3,4) or (2,3,4). Sums: 1+3+4=8, 2+3+4=9. So max sum is 9. Let's simulate our BIT approach that only stores best per value.
Values: [1,2,3,4] ranks 1..4.
Process:
i1: 2 rank2 -> query prefix1 -> (0,0) -> new (1,2) update rank2 (1,2). global: len1 sum2
i2: 1 rank1 -> query prefix0 -> (0,0) -> new (1,1) update rank1 (1,1). global: len1 sum2
i3: 3 rank3 -> query prefix2 -> best over ranks1-2: rank1 (1,1), rank2 (1,2) -> best (1,2) -> new (2,5) update rank3 (2,5). global: len2 sum5
i4: 4 rank4 -> query prefix3 -> best over ranks1-3: rank1 (1,1), rank2 (1,2), rank3 (2,5) -> best (2,5) -> new (3,9) update rank4 (3,9). global: len3 sum9. Works.
Now consider more complex: A = [5, 1, 4, 2, 3, 6]. LIS length? The longest is 4? Let's find: 1,2,3,6 length4; also 1,4,6? length3; 5,6 length2. So LIS length = 4. Which subsequence of length4 gives max sum? Possibly 5? But 5 cannot be in length4 because need 4 increasing numbers after 5? Actually 5 at index1, then 1,4,2,3,6. Can we have 5,? 5 < 6 only, so length2. So the length4 subsequence is 1,2,3,6 sum=12; or 1,4,6? length3; 2,3,6 sum=11; 4,6? So only 1,2,3,6 sum12. Could there be 5,? no. So answer 12.
Our algorithm would produce? Let's simulate: values sorted: [1,2,3,4,5,6] ranks.
i1:5 rank5 -> (1,5) update rank5.
i2:1 rank1 -> (1,1) update rank1.
i3:4 rank4 -> query prefix3: best over ranks1-3: rank1 (1,1) -> (2,5) update rank4? Actually (1,1) -> new (2,5) (since 1+4=5) update rank4.
i4:2 rank2 -> query prefix1: rank1 (1,1) -> new (2,3) update rank2.
i5:3 rank3 -> query prefix2: best over ranks1-2: rank1 (1,1), rank2 (2,3) -> best (2,3) because length2 sum3 > length1 sum1? Actually compare: (2,3) > (1,1) because length larger. So best (2,3) -> new (3,6) update rank3.
i6:6 rank6 -> query prefix5: best over ranks1-5: rank1(1,1), rank2(2,3), rank3(3,6), rank4(2,5), rank5(1,5) -> best (3,6) -> new (4,12) update rank6. global len4 sum12. Good.
Now consider a case that might break: Suppose we have two subsequences ending at value v: one with length 3 sum 100, another with length 4 sum 0. The best is (4,0). For future x > v, to achieve length 5, we need length 4 from v, we would get sum 0+x. But maybe there is another path from some other value w with length 4 sum 200, giving sum 200+x. That's fine. But what about achieving length 4 at x? To get length 4 at x, we need length 3 from some y < x. The best length 3 could be from v with sum 100, but we discarded it because we only kept (4,0) for v. However, we might still have length 3 from other values like u that give sum 120. But if v's length 3 sum 100 is the highest among all length 3 values? But we lost it. Could that cause missing the optimal sum for length 4 at x? Let's construct an explicit example where the maximum sum for length L (global LIS) depends on a subsequence of length L-1 that is not the longest for its ending value.
We need a sequence such that:
There is a value v that appears.
There are two increasing subsequences ending at v: one with length L-1 and high sum, another with length L (longer) but low sum.
Later, there is a value x > v that can extend both: from the length L-1 we get length L at x with sum high+v? Actually we need length L at x, so we need previous length L-1. The length L-1 at v gives length L at x. The length L at v gives length L+1 at x, which could be longer than L, potentially making the global LIS longer. So if length L+1 exists, then the maximum LIS length becomes L+1, and we would be interested in that length, not L. So in that case, we might want to consider length L+1. However, if the length L at v is not enough to achieve a longer global LIS? Wait, we need to think: The global LIS length is the maximum possible length overall. If we can achieve length L+1 by extending the length L from v, then the global LIS length is at least L+1. So the final length we care about is L+1. Then we want max sum for length L+1. The length L-1 path at v might lead to length L at x, which is not the maximum length (since L+1 exists). So we don't care about length L if L+1 is achievable. So the only length that matters is the maximum L_max. So we only need to consider subsequences that lead to L_max. To achieve L_max, we must at each step use a subsequence whose length is the maximum possible to eventually reach L_max? Actually, to get a subsequence of length L_max, we need to follow a chain of extensions where each step increases length by 1. So at the penultimate step, we need a subsequence of length L_max-1 ending at some value less than the last element. That subsequence of length L_max-1 might not be the longest for its ending value if there is an even longer subsequence ending at that same value (which would be length L_max? Actually, if there is a subsequence ending at that value of length L_max, then extending that would give length L_max+1, contradicting L_max being maximum. So at the penultimate value, the maximum length ending at that value cannot exceed L_max-1, because if it were L_max, then you could extend by the last element (if last element > value) to get L_max+1, making L_max not maximum. So in a value that appears before the last element, if there is a subsequence of length L_max, then the overall LIS length would be at least L_max+1, provided there exists a later larger element. But if there is no later larger element, then that value might be the last in some subsequence. But if we are building a subsequence of length L_max, the last element's value may be such that no larger element exists after it. However, we consider the global L_max as maximum possible length. So for any intermediate value, the maximum length of a subsequence ending at that value can be at most L_max, but if it is exactly L_max, then that subsequence is itself a LIS of length L_max, and it doesn't need extension. But if we want to achieve a LIS that ends with a later element, the intermediate values must have length at most L_max-1. So it's possible that for some value, we have both length L_max-1 (high sum) and length L_max (low sum). The length L_max is already a full LIS, but its sum is low. However, there might be a different LIS of length L_max that ends with a later element and uses the length L_max-1 from that value to get a higher sum. But if the value has a length L_max subsequence, it means there exists an increasing subsequence of length L_max that ends at that value. That subsequence itself already uses some elements before that value. To extend to a later element x > v, we could take that length L_max subsequence and append x to get length L_max+1, which would contradict L_max being maximum unless x <= v or not strictly greater. If x > v, then indeed we can extend to L_max+1, making L_max+1 the new maximum. So if there exists a value v with a subsequence of length L_max and there exists a later element x > v, then the overall LIS length is at least L_max+1. Therefore, in a scenario where L_max is the true maximum, it must be that for any value v that appears before the last element of some LIS, the maximum length ending at v is at most L_max-1 if there is a later element that can extend it. Actually, if the overall maximum length is L_max, then for any value v, the maximum length ending at v is ≤ L_max. And if it's exactly L_max, then either v is the last element of some LIS, or there is no later element > v (otherwise we could extend). So in the process of building a LIS that ends at the final element (which is part of the maximum length subsequence), the values along the chain will have lengths that are exactly the position in the chain: the first selected element has length 1, second length 2, ... up to L_max. So for each such value, the maximum length ending at that value is exactly that chain's length (since if there were a longer subsequence ending at that same value, you could combine with later elements to get longer than L_max). So in the optimal chain, the stored best for each value along the chain is exactly the chain's length, and it's the maximum for that value. Therefore, we only need to keep the best (max length) for each value. Because any lower length at that value cannot be part of a chain that yields the maximum LIS length, because if there existed a chain that uses a lower length at that value, then at that value you could replace the prefix with the longer length prefix (since both end at the same value, and the longer prefix has more elements, and the later elements are all greater than that value, so they can be appended to the longer prefix as well? Wait, careful: Suppose we have a value v, and we have two subsequences ending at v: one of length L1 with sum S1, and another of length L2 with sum S2, where L2 > L1. For any future element x > v, we can extend both to lengths L1+1 and L2+1 respectively. The L2+1 length is longer. So if we are aiming for maximum length L_max, we would never use the L1 prefix because it yields shorter final length. However, could there be a scenario where using the L1 prefix yields a final length L_max (same as using L2 prefix) because the L2+1 might not be achievable due to constraints? That would require that L2+1 > L_max, i.e., L2 = L_max, but then L1+1 could be ≤ L_max. But if L2 = L_max, then v already has a subsequence of length L_max. To get a subsequence of length L_max ending at a later element x, we need a prefix of length L_max-1 ending at some y < x. If we use v with length L_max, we would need a later element > v to get length L_max+1, which would be longer than L_max, contradicting L_max being maximum. So if L_max is truly maximum, then there cannot exist a v with a subsequence of length L_max and also a later element x > v; otherwise L_max+1 would exist. Thus, for any v that appears before some element that can extend to L_max, the maximum length at v must be less than L_max. So along any optimal chain for length L_max, each intermediate value's maximum length is exactly the chain length at that point (since if there were a longer subsequence ending at that value, it would yield a longer overall chain, contradiction). Therefore, we only need to keep the best (max length) for each value; the lower lengths are irrelevant for constructing a chain of maximum length because they would lead to a shorter final length or could be replaced by a longer prefix without hurting the sum? But sum might be lower. Could using a longer prefix at the same value reduce the final sum? Possibly, if the longer prefix has a lower sum than the shorter one. For maximum sum among L_max subsequences, we might prefer a shorter prefix with higher sum if it still leads to length L_max? But if we replace a shorter prefix with a longer prefix, the final length becomes longer. To keep final length L_max, we must use a prefix of length exactly L_max-1 at the penultimate value. If we have a value v with two possible prefixes: one of length L_max-1 with high sum, and another of length L_max with low sum. The length L_max prefix cannot be used because it would require final length L_max+1 to be maximum, but if L_max+1 is not possible (because there is no later element > v), then v might be the last element itself. But we are considering v as a value that appears before the last element in the chain. For a chain ending at x (last element), the prefix before x is some value v < x with length L_max-1. At v, there might exist both a length L_max-1 prefix and a length L_max prefix. The length L_max prefix would be a full LIS ending at v. Since v < x, we could extend the length L_max prefix with x to get a subsequence of length L_max+1, unless there is some reason that we cannot (maybe x is not > v? but x > v by condition). So yes, if there exists a length L_max subsequence at v and a later element x > v, then we can get length L_max+1. That would mean the overall LIS length is at least L_max+1, contradicting L_max being maximum. Therefore, in a sequence where L_max is the true maximum length, it cannot be that there exists a value v with a subsequence of length L_max and also a later element greater than v. So for any v that is not the last element of the overall LIS (i.e., there exists some x > v that is part of some LIS chain), the maximum length at v must be < L_max. Actually, it could be exactly L_max if v is the last element of some LIS, but then there is no later element > v that is part of that LIS, but there could be later elements greater than v that are not part of that LIS? If there exists any later element greater than v, then we could extend the LIS ending at v to include that element, yielding length L_max+1, which would contradict L_max being maximum. So if v is the last element of a LIS of length L_max, then there is no element after v that is greater than v. That's possible: v is the maximum element in the entire sequence, or at least after its position there are no larger elements. So for such v, we don't need to extend it. So for values that are not the maximum element (or not the tail), the longest subsequence ending at them must be less than L_max.
Therefore, along any chain that achieves length L_max, each intermediate value's best length is exactly the chain length at that point (since if there were a longer subsequence ending at that value, it would be of length > chain length, leading to a longer overall chain when combined with later elements). So the best (max length) for each value is what we need to use to achieve L_max. Moreover, among those best lengths, we also need the maximum sum for that length. But the best pair we store is (max length, max sum for that length). However, if there are multiple subsequences ending at the same value with the same maximum length, we keep the one with maximum sum. That's exactly what we need for that value when building chains of that maximum length. Could there be a situation where a value v has maximum length L1, but to achieve overall L_max, we need to use a subsequence ending at v of length L1 (since it's the max) but maybe we need to use a different subsequence of length L1 that has a lower sum? Actually, we would always prefer the one with higher sum for the same length L1, because that yields higher total sum when extended. So storing the max sum for the max length is sufficient.
But wait: Could there be a case where the best sum for length L_max comes from a chain where at some intermediate value, the subsequence used has length less than the maximum possible for that value, but still eventually reaches L_max? For that to happen, at that value v, the maximum length possible is L_v > the length we use (say L_used). Then L_used < L_v. Since L_v > L_used, there exists a longer subsequence ending at v. Since v is less than later values in the chain, that longer subsequence could be extended through the same later values to yield a final length greater than L_max (since L_v + (remaining steps) > L_used + (remaining steps) = L_max). That would contradict L_max being maximum. Therefore, such a scenario cannot occur if L_max is truly the maximum LIS length. Because if we can extend from v with remaining k steps (including the last element) to reach L_max, then using the longer prefix of length L_v would yield length L_v + k > L_used + k = L_max. Since the later values are all > v and appear after, the extension is possible, so we could achieve a longer increasing subsequence, contradicting maximality. Hence, in any optimal LIS chain, at each intermediate value, the length of the prefix must be the maximum possible length for that value. Therefore, keeping only the maximum length for each value suffices.
Thus the BIT storing best (length, sum) per value should be sufficient to compute the maximum sum among LIS.
I recall that the problem "Longest Increasing Subsequence with maximum sum" is a known problem, and the typical solution is to compute LIS length using patience and then use DP with segment tree storing maximum sum for each length? Let's search memory: There is a problem on Codeforces "D. Longest Subsequence" maybe not. But I've seen solutions using segment tree with pair (len, sum). So I think it's correct.
Nevertheless, we should test with some more edge cases, especially with duplicate values and negative numbers.
Case: A = [-5, -4, -3, -2]. LIS length = 4, sum = -14. Our algorithm: Process:
i1:-5 rank1 -> query0 -> (0,0) -> (1,-5) update rank1. global len1 sum -5.
i2:-4 rank2 -> query1 -> best rank1 (1,-5) -> (2,-9) update rank2. global len2 sum -9.
i3:-3 rank3 -> query2 -> best (2,-9) -> (3,-12) update rank3. global len3 sum -12.
i4:-2 rank4 -> query3 -> best (3,-12) -> (4,-14) update rank4. global len4 sum -14. Output -14. Correct.
Case: A = [10, 20, 10, 30]. LIS length = 3 (10,20,30) or (10,10? not allowed because equal). Actually 10,20,30 from indices 1,2,4 sum=60. Also 10,10? not allowed. Also 10,30 from index3? But 10 (index3) cannot extend from earlier 10 because equal. So LIS length 3. Our algorithm:
Values: [10,20,30] ranks: 10->1,20->2,30->3.
i1:10 rank1 -> (1,10) update.
i2:20 rank2 -> query1: (1,10) -> (2,30) update rank2.
i3:10 rank1 -> query0 -> (1,10) new (1,10) but same as existing? update does nothing.
i4:30 rank3 -> query2: best over ranks1-2: rank1 (1,10) rank2 (2,30) -> best (2,30) -> (3,60) update rank3. global len3 sum60. correct.
Now consider a scenario where there are two different subsequences both of length L_max, but one uses a value that has a longer alternative subsequence, but that longer alternative cannot extend because later elements are not larger? But if the longer alternative exists ending at v, and v is used in the L_max chain as an intermediate, there must be later elements > v, so it can extend. So it would create longer LIS. So cannot.
Thus approach is sound.
Now we just need to implement efficiently.
Potential pitfalls: Since we are using BIT with two separate arrays, we need to ensure the "max" operation is applied correctly. For update, we compare new pair with current bit node and update if better. But note: BIT nodes store aggregated max over a range, not necessarily the best for that specific point. However, the logic we use for update is: at position pos, we want to incorporate the new point value into the BIT. The standard BIT update for max operation is: while pos <= M: bit[pos] = max(bit[pos], value); pos += lowbit(pos). That works because we are effectively saying the maximum over the range that node covers should be at least value. So we don't need to know the exact point; we just raise the node's max if needed. This works as long as we never need to lower a node's max. Since we only ever increase the maximum (in lex order), it's safe.
But careful: The lex order comparison: We need to define a custom max function. For BIT update, we compare the new pair with the stored pair and replace if the new is better. For query, we combine pairs from nodes with the same comparison. Since we never decrease, it's fine.
But there is nuance: When we update a point multiple times with increasing pairs, the node's stored max might become a pair that is from a different point but still valid. However, later we might get a new pair for the same point that is even better, and we update the node with it. That's fine.
But consider a scenario: At a node covering range R, the current max is from point p in R with pair (len,sum). Later, we get a new pair for a different point q in R that is worse than the current max; we do an update with the worse pair; the node's max remains the same. That's okay. If later, the point p's pair becomes invalid because we discover an even better pair for p? But that would be an update with a better pair for p, which would raise the node's max further. So the node's max only increases.
Thus BIT works.
Now we need to be mindful of Python recursion or speed. We'll implement iterative BIT.
Now, we should also consider that N might be up to 2e5, but A values might be up to 1e9. Compression is fine.
Now, finalize solution.
However, there is also a known alternative: use patience sorting with piles, where each pile stores the minimum possible last value for a given length, and also the maximum sum achievable for that length? But I think BIT is simpler.
Let's also test with a more complex case:
A = [2, 4, 3, 5, 1, 6, 7]. LIS length? 2,4,5,6,7 length5 sum=24; 2,3,5,6,7 length5 sum=23; 1,3,5,6,7 length5 sum=22; 2,4,5,6,7 is best? 2+4+5+6+7=24; 2+4+5+6+7? Actually 2,4,5,6,7 =24; 3,5,6,7 is length4; So answer 24.
Our algorithm:
Values sorted: [1,2,3,4,5,6,7] ranks.
Process:
i1:2 rank2 -> (1,2) update2.
i2:4 rank4 -> query3: best over ranks1-3: rank2 (1,2) -> (2,6) update4.
i3:3 rank3 -> query2: best over ranks1-2: rank2 (1,2) -> (2,5) update3.
i4:5 rank5 -> query4: best over ranks1-4: we have rank2(1,2), rank3(2,5), rank4(2,6) -> best (2,6) (len2 sum6) -> (3,11) update5.
i5:1 rank1 -> query0 -> (1,1) update1.
i6:6 rank6 -> query5: best over ranks1-5: rank1(1,1), rank2(1,2), rank3(2,5), rank4(2,6), rank5(3,11) -> best (3,11) -> (4,17) update6.
i7:7 rank7 -> query6: best over ranks1-6: best (4,17) -> (5,24) update7. Output 24. correct.
Now test with negative and positive mix: A = [10, -5, 8, 3, 6, 9]. LIS length? Let's find increasing subsequences: -5,3,6,9 length4 sum=13; 3,6,9 length3 sum=18? Actually 3+6+9=18 but length3; 8,9 length2 sum=17; 10? 10>9 so can't extend; So LIS length=4 (-5,3,6,9 sum=13). But could there be 10? Not length4. So answer 13.
Our algorithm:
Sorted: [-5,3,6,8,9,10] ranks: -5:1,3:2,6:3,8:4,9:5,10:6.
Process:
i1:10 rank6 -> query5: none? initially all zero -> (1,10) update6. global len1 sum10.
i2:-5 rank1 -> query0 -> (1,-5) update1. global? len1 max sum=10.
i3:8 rank4 -> query3: best over ranks1-3: rank1 (1,-5) -> (2,3) update4. global len2 sum3.
i4:3 rank2 -> query1: rank1 (1,-5) -> (2,-2) update2. global len2 sum3 (still).
i5:6 rank3 -> query2: best over ranks1-2: rank1 (1,-5), rank2 (2,-2) -> best (2,-2) -> (3,4) update3. global len3 sum4.
i6:9 rank5 -> query4: best over ranks1-4: rank1(1,-5), rank2(2,-2), rank3(3,4), rank4(2,3) -> best (3,4) -> (4,13) update5. global len4 sum13. Output13. correct.
Now test scenario where two subsequences of same length L_max but one uses a different intermediate value that is not the best for that value? Already argued it's covered.
Now we need to verify with a tricky case I thought of: A = [2, 3, 1, 4]. LIS length? 2,3,4 length3 sum=9; 1,4? length2; 2,4? length2; 3,4 length2; 1,4 length2; 2,3,4 sum9; 1,3,4 sum8; So answer 9. Our algorithm:
Values [1,2,3,4] ranks.
i1:2 rank2 -> (1,2) update2.
i2:3 rank3 -> query2: best (1,2) -> (2,5) update3.
i3:1 rank1 -> (1,1) update1.
i4:4 rank4 -> query3: best over ranks1-3: rank1(1,1), rank2(1,2), rank3(2,5) -> best (2,5) -> (3,9) update4. Output9. Good.
Now consider scenario with duplicate and longer chain: A = [1, 2, 1, 3, 2, 4]. LIS length = 4? (1,2,3,4) sum=10. Also (1,2,3,4) from different indices sum=10. There is also (1,2,4?) length3. So answer 10. Our algorithm should compute.
Alright.
Now we need to produce final code.
Potential improvements: Use list of tuples for BIT, but two separate integer lists is faster.
We'll implement:
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data: return
it = iter(data)
n = int(next(it))
A = [int(next(it)) for _ in range(n)]
# compression
uniq = sorted(set(A))
rank = {v:i+1 for i,v in enumerate(uniq)} # 1-indexed
m = len(uniq)
bit_len = [0](m+2) # extra
bit_sum = [0](m+2)
code
def better(a_len, a_sum, b_len, b_sum):
# return True if (a_len, a_sum) is better than (b_len, b_sum)
return a_len > b_len or (a_len == b_len and a_sum > b_sum)
def update(pos, length, sum_val):
while pos <= m:
if better(length, sum_val, bit_len[pos], bit_sum[pos]):
bit_len[pos] = length
bit_sum[pos] = sum_val
pos += pos & -pos
def query(pos):
best_len = 0
best_sum = 0
while pos > 0:
if better(bit_len[pos], bit_sum[pos], best_len, best_sum):
best_len = bit_len[pos]
best_sum = bit_sum[pos]
pos -= pos & -pos
return best_len, best_sum
global_best_len = 0
global_best_sum = 0
for x in A:
r = rank[x]
prev_len, prev_sum = query(r-1)
new_len = prev_len + 1
new_sum = prev_sum + x
update(r, new_len, new_sum)
if new_len > global_best_len or (new_len == global_best_len and new_sum > global_best_sum):
global_best_len = new_len
global_best_sum = new_sum
# output
sys.stdout.write(str(global_best_sum) + "\n")
Now, we must consider that the BIT update might need to consider that the new pair could be better than the current stored at that point, but the BIT node might have a better pair from another point. However, we are updating with the new pair. If the new pair is not better than the node's current max, we don't change it. If it is better, we set it. But what if the node's current max comes from a point that is not the one we are updating, and the new pair is better, then the node's max becomes the new pair, which is correct because the new pair is the new maximum over that node's range. So it's fine.
Now, one more nuance: The BIT query returns the max over prefix. But we are updating nodes with max. However, suppose at a node covering range [l, r], the max stored is from a point that has a certain (len,sum). Later, we update a different point within [l, r] with a better pair; we update the node to that better pair. Good. Later, we update the original point with an even better pair; we again update the node to the new better pair. So it's consistent.
Now, we need to be careful about the base case: query(0) returns (0,0). Works.
Now, what about negative sums? The base sum 0 might be better than negative sums for length 0. But when we compute new sums, they may be negative. That's okay.
Now, verify with a scenario where there are multiple possible LIS and we need to output max sum. Already did.
Now, I want to test a more complex case where the DP may incorrectly choose a prefix with longer length but lower sum that later yields a higher sum for the final length? That cannot happen because longer prefix always yields longer final length, but if the final length is capped at L_max, maybe the longer prefix yields length > L_max and we don't care? But if longer prefix yields length > L_max, then L_max is not the maximum. So that scenario contradicts L_max being maximum. So not possible.
Now, I recall a known problem: "Longest Increasing Subsequence with maximum sum" is sometimes solved by computing LIS lengths first, then using DP that only considers elements that are part of some LIS. But the BIT approach should work.
Now, confirm with a random test via mental reasoning: Let's construct a tricky example:
A = [1, 5, 2, 3, 4]. LIS length? 1,2,3,4 length4 sum=10; 1,2,3,4 also from 1,2,3,4 sum=10; 5? cannot be part of length4. So answer 10.
Our algorithm:
Values: [1,2,3,4,5] ranks.
i1:1 rank1 -> (1,1) update1.
i2:5 rank5 -> query4: best over ranks1-4: rank1 (1,1) -> (2,6) update5.
i3:2 rank2 -> query1: rank1 (1,1) -> (2,3) update2.
i4:3 rank3 -> query2: best over ranks1-2: rank1 (1,1), rank2 (2,3) -> best (2,3) -> (3,6) update3.
i5:4 rank4 -> query3: best over ranks1-3: rank1(1,1), rank2(2,3), rank3(3,6) -> best (3,6) -> (4,10) update4. global len4 sum10. OK.
Now consider: A = [2, 1, 3, 4]. Already did.
Now consider: A = [1, 100, 2, 101, 3, 102]. LIS length? 1,2,3,102? Actually we can have 1,2,3,102 length4. Also 1,100,101,102 length4 sum=304; 1,2,101,102 length4 sum=206; etc. Max sum should be 1+100+101+102=304. Let's test algorithm:
Sorted: [1,2,3,100,101,102] ranks: 1->1,2->2,3->3,100->4,101->5,102->6.
i1:1 rank1 -> (1,1) update1.
i2:100 rank4 -> query3: best over ranks1-3: rank1 (1,1) -> (2,101) update4. (Note: 1+100=101)
i3:2 rank2 -> query1: rank1 (1,1) -> (2,3) update2.
i4:101 rank5 -> query4: best over ranks1-4: rank1(1,1), rank2(2,3), rank4(2,101) -> best (2,101) -> (3,202) update5.
i5:3 rank3 -> query2: best over ranks1-2: rank1(1,1), rank2(2,3) -> best (2,3) (since len2 sum3 > len1 sum1) -> (3,6) update3.
i6:102 rank6 -> query5: best over ranks1-5: rank1(1,1), rank2(2,3), rank3(3,6), rank4(2,101), rank5(3,202) -> best (3,202) -> (4,304) update6. global len4 sum304. correct.
Now consider a case where there is a choice between two prefixes of same length but different sums that lead to the same final length but different sums. Our algorithm picks the max sum at each value for that length (since we update with max sum for that length). That should propagate correctly.
Now consider: A = [1, 2, 100, 3, 4, 5]. LIS length? 1,2,3,4,5 length5 sum=15; but 1,2,100,? can't extend because 3,4,5 are less than 100? Actually 100 is greater than 3,4,5 so cannot have 100 before 3,4,5 if we need increasing. So 100 cannot be part of length5. So only 1,2,3,4,5 sum=15. However, there is 1,2,100? length3 sum=103, but not longest. So answer 15. Our algorithm:
Sorted: [1,2,3,4,5,100] ranks.
i1:1 -> (1,1)
i2:2 -> query1: (1,1) -> (2,3)
i3:100 -> query? rank6? Actually 100 rank6? Wait sorted: [1,2,3,4,5,100] -> rank of 100 is 6. query5: best among ranks1-5: we have rank1(1,1), rank2(2,3) -> best (2,3) -> (3,103) update rank6.
i4:3 rank3 -> query2: best rank2(2,3) or rank1(1,1) -> best (2,3) -> (3,6) update rank3.
i5:4 rank4 -> query3: best among ranks1-3: rank1(1,1), rank2(2,3), rank3(3,6) -> best (3,6) -> (4,10) update rank4.
i6:5 rank5 -> query4: best among ranks1-4: rank4(4,10) etc -> (5,15) update rank5. global len5 sum15. correct.
Now consider case where there is a longer LIS that uses lower sum early but higher later? But our DP selects max sum for each length at each value, so should get max total.
Thus solution appears correct.
Now, we need to output just the maximum sum, with newline.
Now, consider potential overflow of sum: Python int is fine.
Now, about reading input: Use sys.stdin.buffer for speed.
Now, confirm constraints: The problem statement didn't provide constraints, but typical problems may have N up to 2e5. So O(N log N) is fine.
Now, let's test with an extreme: N=200000, all distinct increasing sequence 1..200000. Then LIS length = N, sum = N(N+1)/2 which is about 2e10, fine. The BIT updates and queries O(log N) each, total O(N log N) ~ 200k * 18 = 3.6M operations, fine in Python.
Now, we must ensure that the BIT arrays for length and sum are of appropriate size. Use list of ints.
Now, one more nuance: The BIT update function as implemented uses a while loop and a comparison that may be slower due to function call overhead. But it's okay.
We can micro-opt: define local variables for bit_len, bit_sum, better as inline conditions.
Now, let's produce final answer.
But before finalizing, I want to double-check the logic about storing only best per value with lex order. I want to prove more formally.
We define DP(v) as best pair (length, sum) for any increasing subsequence ending with value v (from processed elements). We claim that for the purpose of computing future best pairs, it's sufficient to keep only the pair with maximum length, and among those maximum length, maximum sum. Because for any future value w > v, we only care about the best possible extension. Suppose we have two pairs p1=(L1,S1) and p2=(L2,S2) with L1 > L2. Then for any w, the resulting lengths are L1+1 and L2+1, with L1+1 > L2+1. So p1 yields longer subsequence. Therefore, for maximizing final length, p1 is always better. If the maximum length overall is L_max, and we are only interested in subsequences of length L_max, then any prefix that yields length less than L_max-? Actually, to achieve length L_max ending at w, we need a prefix of length L_max-1. If L1 > L_max-1, then p1 gives length > L_max-1, which would yield length > L_max when extended, contradicting L_max being maximum if w exists after. So such p1 cannot be used if we want exactly L_max (but if L_max is the maximum, then there is no w that can extend p1 to L_max+1; but if there is w > v, then extending p1 would give L1+1. If L1+1 > L_max, then L_max is not maximum. So in a maximum LIS scenario, for any v that has a later w > v in the LIS chain, we must have L1 <= L_max-1. Thus the best length at v is at most L_max-1. And for any v, the best pair we store is with length L_best(v). If L_best(v) is less than L_max-1, it could still be used as a prefix for some chain that yields L_max? Possibly if the remaining steps are enough. But if there exists a chain that yields L_max and uses v as an intermediate, then the length at v must be exactly the position in the chain, say k. Since the chain yields L_max, we have k + remaining = L_max. If there is another subsequence ending at v with length > k, then that would be L_best(v) > k. Then we could replace the prefix in the chain with that longer subsequence, obtaining a length L_best(v) + remaining > L_max, contradiction. Therefore, L_best(v) must equal k. So the best pair at v is exactly the one we need (with length k). And among those with length k, we want the maximum sum. So storing best (max length, max sum for that length) gives the optimal prefix for any chain that uses v at that exact length required for L_max. So the DP is correct.
Hence solution stands.
Now final code.
We'll add a main guard.
We'll also consider using array module or just lists.
Now final answer: Provide Python code with solve() function.
Potential improvements: Use sys.setrecursionlimit but not needed.
We'll produce final message. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
a = [int(next(it)) for _ in range(n)]
code
# coordinate compression
uniq = sorted(set(a))
rank = {v: i+1 for i, v in enumerate(uniq)} # 1‑based
m = len(uniq)
# Fenwick tree stores (length, sum) pairs, initially (0,0)
bit_len = [0] * (m + 2)
bit_sum = [0] * (m + 2)
def better(l1, s1, l2, s2):
"""return True if (l1,s1) is lexicographically larger than (l2,s2)"""
return l1 > l2 or (l1 == l2 and s1 > s2)
def update(pos: int, length: int, sm: int):
"""point update: try to improve the value at position pos"""
while pos <= m:
if better(length, sm, bit_len[pos], bit_sum[pos]):
bit_len[pos] = length
bit_sum[pos] = sm
pos += pos & -pos
def query(pos: int):
"""prefix query: best pair over indices 1..pos"""
best_len = 0
best_sum = 0
while pos > 0:
if better(bit_len[pos], bit_sum[pos], best_len, best_sum):
best_len = bit_len[pos]
best_sum = bit_sum[pos]
pos -= pos & -pos
return best_len, best_sum
best_global_len = 0
best_global_sum = 0
for x in a:
r = rank[x]
prev_len, prev_sum = query(r - 1) # best ending with a smaller value
new_len = prev_len + 1
new_sum = prev_sum + x
update(r, new_len, new_sum) # store new candidate
if new_len > best_global_len or (new_len == best_global_len and new_sum > best_global_sum):
best_global_len = new_len
best_global_sum = new_sum
sys.stdout.write(str(best_global_sum) + "\n")