ENع
→LIS
الدرس 42 · Dynamic programming and backtracking

Longest increasing subsequence

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

Find the longest run of numbers that keeps rising, skipping any you like. Checking every subsequence costs 2ⁿ. Dynamic programming needs one number per position instead: the length of the best rising run that ends there. Watch a table fill for 3 1 4 1 5 9 2 6, read off the answer, walk back to the run itself, count the Θ(n²) cost, then meet the Θ(n log n) tails method. The Software lesson on dynamic programming covers memoisation and tables, and "Longest common subsequence and edit distance" shows another table built over a sequence.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 42 · تفاعلي
01 / 10

Pick a rising subsequence

A subsequence keeps some numbers, in order, and may skip the rest. We want the longest one where each number is bigger than the one before. In 3 1 4 1 5 9 2 6, one answer is 3 4 5 9: length 4.

a = [3, 1, 4, 1, 5, 9, 2, 6]
i        0   1   2   3   4   5   6   7
a        3   1   4   1   5   9   2   6

increasing subsequence: positions i₁ < i₂ < … with
a[i₁] < a[i₂] < …   (strictly bigger each time)
example: positions 0, 2, 4, 5 → 3 4 5 9
longest length: 4 (brute force over all 2^8 = 256 subsets agrees)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Pick a rising subsequence

    A subsequence keeps some numbers, in order, and may skip the rest. We want the longest one where each number is bigger than the one before. In 3 1 4 1 5 9 2 6, one answer is 3 4 5 9: length 4.

    a = [3, 1, 4, 1, 5, 9, 2, 6]
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    
    increasing subsequence: positions i₁ < i₂ < … with
    a[i₁] < a[i₂] < …   (strictly bigger each time)
    example: positions 0, 2, 4, 5 → 3 4 5 9
    longest length: 4 (brute force over all 2^8 = 256 subsets agrees)
  2. The state: runs ending here

    Trying every subsequence means 2ⁿ choices: 256 for n = 8. Instead keep one number per position. L[i] is the length of the longest rising run that ends exactly at a[i]. Fixing the end helps: the next number only has to beat a[i].

    state:  L[i] = length of the longest increasing
            subsequence that ENDS at position i
    
    why the end: a run ending at a[i] can be extended by
    any later a[k] > a[i]; nothing else about it matters
    
    subproblems: 8 (one per position) instead of 2^8 = 256
  3. Base case: every number alone

    Any single number is a rising run of length 1, so every cell starts at 1. Line 2 builds that table: L = [1] * len(a). The real work is deciding which cells can grow.

    line 2:  L = [1] * len(a)
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    L        1   1   1   1   1   1   1   1
    
    base case: a run of one number has length 1
  4. Look back from 4

    Fill L left to right. 3 and 1 have nothing smaller before them, so they keep 1. For a[2] = 4, look back: 3 < 4 and 1 < 4, so 4 extends either run. Both have length 1, so L[2] = 2.

    i = 0:  no earlier j                       L[0] = 1
    i = 1:  j = 0: 3 < 1? no                   L[1] = 1
    i = 2:  j = 0: 3 < 4? yes  L[0] + 1 = 2
            j = 1: 1 < 4? yes  L[1] + 1 = 2    L[2] = 2
    
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    L        1   1   2   ·   ·   ·   ·   ·
  5. Equal is not bigger

    a[3] = 1. Nothing before it is smaller: 1 < 1 is false, as a rising run must strictly increase. So L[3] stays 1. Full rule: L[i] = 1 + the largest L[j] with j < i and a[j] < a[i], or 1 if none.

    i = 3:  j = 0: 3 < 1? no
            j = 1: 1 < 1? no   (equal is not smaller)
            j = 2: 4 < 1? no                   L[3] = 1
    
    transition:
      L[i] = 1 + max( L[j] : j < i and a[j] < a[i] )
      L[i] = 1 when no such j exists
    
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    L        1   1   2   1   ·   ·   ·   ·
  6. Fill the rest

    The same rule fills the rest. 5 extends 4, so L[4] = 3. 9 extends 5: 4. 2 extends a 1: 2. 6 extends 5: 4. Each cell reads only cells to its left, and those are already final.

    i = 4 (a = 5):  smaller at j = 0, 1, 2, 3  best L[2] = 2  → L[4] = 3
    i = 5 (a = 9):  smaller at j = 0, 1, 2, 3, 4  best L[4] = 3  → L[5] = 4
    i = 6 (a = 2):  smaller at j = 1, 3  best L[1] = 1  → L[6] = 2
    i = 7 (a = 6):  smaller at j = 0, 1, 2, 3, 4, 6  best L[4] = 3  → L[7] = 4
    
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    L        1   1   2   1   3   4   2   4
    
    order matters: L[i] only reads L[0..i-1], already final
  7. The answer is max(L)

    The longest run can end anywhere, so the answer is the largest value in the table, not simply the last one: max(L) = 4. Two cells reach it: L[5] (runs ending at 9) and L[7] (runs ending at 6).

    line 7:  return max(L)
    i        0   1   2   3   4   5   6   7
    a        3   1   4   1   5   9   2   6
    L        1   1   2   1   3   4   2   4
    
    max(L) = 4, reached at i = 5 and 7
    a run may end anywhere, so check every cell
  8. Walk back to the run

    To get the run, walk back from a cell with L = 4. Each time, find an earlier smaller number whose L is one less. From 6: 5 (L = 3), then 4 (L = 2), then 1. The run is 1 4 5 6.

    from i = 7 (a = 6, L = 4):  need a[j] < 6 and L[j] = 3  → j = 4 (a = 5)
    from i = 4 (a = 5, L = 3):  need a[j] < 5 and L[j] = 2  → j = 2 (a = 4)
    from i = 2 (a = 4, L = 2):  need a[j] < 4 and L[j] = 1  → j = 1 (a = 1)
    
    run: positions 1, 2, 4, 7 → 1 4 5 6
    scan j from i − 1 down; other choices give other runs
    of the same length (3 4 5 9, 1 4 5 9, 3 4 5 6 …)
  9. Cost: Θ(n²) time

    For each i, line 4 loops over every earlier j, so line 5 runs 0 + 1 + … + 7 = 28 times for n = 8. In general that is n(n − 1)/2 checks: Θ(n²) time. The table L adds Θ(n) memory.

    checks on line 5, by i:
      0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
      n(n − 1)/2 = 8·7/2 = 28
    
    time:  Θ(n²)   (two nested loops over prefixes)
    space: Θ(n)    (the table L)
    n = 1000 → 499500 checks
  10. Faster: smallest tails

    Faster: keep tails[k], the smallest end of any rising run of length k + 1. Each number replaces the first tail not smaller than it (binary search), or is added at the end. The answer is the count of tails: 4, in Θ(n log n).

    x = 3:  k = 0  append      tails = [3]
    x = 1:  k = 0  replace 3   tails = [1]
    x = 4:  k = 1  append      tails = [1, 4]
    x = 1:  k = 0  replace 1   tails = [1, 4]
    x = 5:  k = 2  append      tails = [1, 4, 5]
    x = 9:  k = 3  append      tails = [1, 4, 5, 9]
    x = 2:  k = 1  replace 4   tails = [1, 2, 5, 9]
    x = 6:  k = 3  replace 9   tails = [1, 2, 5, 6]
    
    length = len(tails) = 4
    tails stays sorted, so bisect_left finds k in Θ(log n)
    
    from bisect import bisect_left
    def lis_fast(a):
        tails = []
        for x in a:
            k = bisect_left(tails, x)
            if k == len(tails):
                tails.append(x)
            else:
                tails[k] = x
        return len(tails)

اختبار يتاح بعد الخطوة الأخيرة.