标签:cas when ber sea ssi 4.0 change sam with
300. Longest Increasing Subsequence
https://leetcode.com/problems/longest-increasing-subsequence/solution/
Solution 1: dp
Time O(n^ 2)
Solution 2: binary search n* logn.
below is the example i copied from dragon, so my understanding is that the correct subsequence is 1 6 8 9, when we meet 5 , since 5 is not bigger than the last number of current subsequence, which is 1 6 8, so this means 5 can not be added after 8 to make a longer subsequence, but 5 could be part of the potential longest subsequence in the future, say if there are more numbers after 5 , like 6, 7, 8, 9, 10, 11... so in this case, we want to keep 5 somewhere , just in case we need 5 in the future to make the longest subsequence.
one way to do that is to replace 6 with 5, since we know already the longest subsequnce is 3 (1 6 8), by replacing 6 with 5 , the length is the still same, since we are not adding or removing, we are just replacing. so we basically do two things here, one is to record the current longest subsequent length,
which can be done without keeping the current correct subsequence. but we do keep partial correct subsequence of the longest , globalwise, by replacing 6 with 5, because all numbers later bigger than 5 are defintly bigger than 6, so we are not missing anything, so 5 is a better choice.
another example to help you understand this, after replacing 6 with 5. the current subsequence is 1 5 8 , say 7, 8 comes in after 5,
first when we meet 7, since 7 is smaller than 8, we replace 7 with 8 and the length is still 3 , the current subsequence is 1 5 7
and then when we meet 8, 8 is bigger than 7, so 8 is added after 7, the current subsequence is 1 5 7 8 , which has length 4
imagine we didn‘t replace 8 with 7 when we first meet 7, we still have 1 5 8 ,
and then when we meet 8, since 8 is not bigger than the last element of current subsequence 1 5 8, then 8 is not added after the end of the list
and hopefully you see how we missed the chance to have a longer subsequence when we don‘t replace 8 with 7. and also hope you understand that
replacing elements doesn‘t change the length of the current longest increasing subsequence.
For example, if the nums is
1 6 8 5 9
then the sequence will be like
1
1 6
1 6 8
1 5 8
1 5 8 9
The result will be 4. But the LIS is not 1 5 8 9.
300. Longest Increasing Subsequence
标签:cas when ber sea ssi 4.0 change sam with
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550962.html