Now, what's the rule for that? There should be an edge from a[i] to a[j] if a[j] is greater than a[i] and there is no number between the two -- in other words there is no k such that i < k < j and a[i] < a[k] < a[j]. Here are graphs for each of their examples:
Example 0: {1, 3, 2, 6, 4, 5 }: |
Example 1: {1000000000,100000000,10000000,1000000,100000,10000,1000,100,10,1}:
|
Example 2: {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}
|
Example 3: {564,234,34,4365,424,2234,306,21,934,592,195,2395,2396,29345,13295423,23945,2}
|
Now that you have this graph, what is a maximum subsequence? It's a path from a node with no incoming edges to a node with no outgoing edges. Given that, our job is to determine how many such paths there are. It should be easy to see that the number of paths is 4 in example zero, 10 in example 1, and 1 in example 2. What about example 3? That's a mess!
So, we can be quantitative. There is one path to any node with no incoming edges. Otherwise, the number of paths to a node is the sum of the number of paths to nodes incident to it. In example 1, there is one path to nodes one, three and two. There are two paths to node six and two paths to node four. And thus two paths to node five. So, the sum of paths to nodes with no outgoing edges is four.
How do we calculate this? Using topological sort! We start with nodes with no incoming edges. They have one path. Then we do a topological sort -- every time we process a node, we go through each of its edges, and add its number of paths to the nodes to which it is connected. Then we remove the edges. When we're done, we sum up the number of paths to nodes with no outgoing edges.
I'll put this calculation in all the examples below. I've colored nodes with no outgoing edges magenta. The sum of the values in these nodes is our answer:
Example 0: {1, 3, 2, 6, 4, 5 }: |
Example 1: {1000000000,100000000,10000000,1000000,100000,10000,1000,100,10,1}:
|
Example 2: {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}
|
Example 3: {564,234,34,4365,424,2234,306,21,934,592,195,2395,2396,29345,13295423,23945,2}
|