Consider any two groups, J and I ( j < i and a_j < a_i for all j and i ). In any swap scenario, a_i is the new max for J , and a_j is the new min for I , and J extends to the right, at least to and including I
Now, if any group from I right of I were whos more than the values in the left segment I to I , this group would not be part of I , but rather its own group or part of another group, indicating a higher mark.
Thus, this type of swap will reduce the number of labels by the number of groups between J and I and unite the groups J to I
Now consider a group swap. The only time a character is added if a_i and a_j ( j < i ) are the minimum and maximum, respectively, of two adjacent segments, which leads to the division of the group into these two segments. Banana123 showed in a comment below that this condition is not enough (for example, 3,6,4,5,1,2 => 3,1,4,5,6,2). We can solve this by also checking before the switch that the second smallest I greater than the second largest J
Banana123 also showed in the comment below that in this case more than one character can be added, for example 6,2,3,4,5,1 . We can handle this by storing the min, max record and the number of groups that correspond to the count of consecutive maxes in the segment tree.
Example 1:
(1,6,1)
Change 2 and 5. Updates occur in the log (n) at intervals of 2 and 5. To add the number of groups in a larger interval, the left group max must be lower than the right group min. But if this is not the case in the second example, we must check one level down in the tree.
(1,6,1) (2,6,1) (1,5,1) (6,6,1) (2,3,2) (4,4,1) (1,5,1) 6 2 3 4 5 1
Exchange 1 and 6:
(1,6,6) (1,3,3) (4,6,3) (1,1,1) (2,3,2) (4,4,1) (5,6,2) 1 2 3 4 5 6
Example 2:
(1,6,1) (3,6,1) (1,4,1) (6,6,1) (3,5,1) (4,4,1) (1,2,1) 6 5 3 4 2 1
Change 1 and 6. On the right side, we have two groups, where the left group max is larger than the right group min, (4,4,1) (2,6,2) . To get the exact number of marks, we go down and move 2 to group 4 to get a score of two characters. A similar study is then performed at the level to the top.
(1,6,3) (1,5,2) (2,6,2) (1,1,1) (3,5,1) (4,4,1) (2,6,2) 1 5 3 4 2 6