I encountered this question in my written examination today and found it difficult.
1. Problem description:
Returns the length of the longest monotonic auto-incrementing subsequence of a positive integer sequence. The subsequence is not consecutive. For example
Input: 5
5 2 4 3 1
Output: 2
2. The most intuitive approach to dynamic planning is dynamic planning. Using dp [I] to represent the length of the longest incrementing subsequence ending with the I element, how can we transfer it? Let's take it all into consideration in dp [j] Before I, (j Dp [I]-1, which indicates that dp [I] can be updated based on this j, that is, dp [I] = dp [j] + 1; otherwise, dp [I] does not need to be changed.
Complexity: The O (N ^ 2) code is as follows:
# Include
# Define MAX 100 using namespace std; int dp [MAX]; int val [MAX]; int main () {int n, rs = 1; cin> n; for (int I = 0; I
> Val [I]; dp [I] = 1; // only one element for initialization (int j = 0; j
3 The method described in O (NlogN) algorithm 2 needs to traverse all dp [0] ~ When solving dp [I]. Dp [I-1], so can reduce each traversal?
In fact, when I is a little larger, j =, 2, and so on may not be able to meet the requirements of dp [j]> dp [I]-1, and it is useless to traverse them, after finding a j that meets both of the preceding conditions, we can determine that items smaller than dp [j] do not need to be considered. Therefore, we need to find items that meet val [j].
Using namespace std; vector
Len; // dynamic array int bisearch (int val) {int left = 0, right = len. size (); while (left <= right) {int mid = (left + right)> 1; if (len [mid] <val) left = mid + 1; else right = mid-1;} return left;} int main () {int n, val; cin> n; for (int I = 0; I
> Val; int k = bisearch (val); if (len. size ()
The difficulty of this question is to use an auxiliary array to record the features of each longest incrementing subsequence, and use the greedy idea to store only one ending number.