longest nondecreasing subsequence in O(nlgn)

前端 未结 5 1955
无人及你
无人及你 2021-01-06 04:07

I have the following algorithm which works well

I tried explaining it here for myself http://nemo.la/?p=943 and it is explained here http://www.geeksforgeeks.org/lon

5条回答
  •  长情又很酷
    2021-01-06 04:29

    My Java version:

      public static int longestNondecreasingSubsequenceLength(List A) {
        int n = A.size();
        int dp[] = new int[n];
        int max = 0;
        for(int i = 0; i < n; i++) {
            int el = A.get(i);
            int idx = Arrays.binarySearch(dp, 0, max, el);
            if(idx < 0) {
                idx = -(idx + 1);
            }
            if(dp[idx] == el) { // duplicate found, let's find the last one 
                idx = Arrays.binarySearch(dp, 0, max, el + 1);
                if(idx < 0) {
                    idx = -(idx + 1);
                }
            }
            dp[idx] = el;
            if(idx == max) {
                max++;
            }
        }
        return max;
    }
    

提交回复
热议问题