10/40
Part 2 of 7 · Two statesLearn

Two rows: one for nothing deleted, one for at most one deleted

So the state has two parts: the position, and how many deletions the run has used. Write the four things down:

  1. The cells. run[0][i] is the longest run that ends at a[i] with nothing deleted. run[1][i] is the longest run that ends at a[i] with at most one element deleted from it.
  2. The recurrence. Both rows grow by one when a[i - 1] < a[i]. Row 1 has one more way in: delete a[i - 1] and attach a[i] to a run that ends at a[i - 2]. That run must come from row 0, because this step uses the deletion, and it only works if a[i - 2] < a[i].
  3. The base cases. A run of one element: every cell starts at 1.
  4. The order. Left to right. Each cell reads only positions i - 1 and i - 2.
def longest_run_one_out(a):
    n = len(a)
    if n == 0:
        return 0
    # run[d][i]: the longest run ending at a[i], at most d deleted
    run = [[1] * n, [1] * n]
    for i in range(1, n):
        if a[i - 1] < a[i]:
            run[0][i] = run[0][i - 1] + 1
            run[1][i] = run[1][i - 1] + 1
        if i >= 2 and a[i - 2] < a[i]:
            # delete a[i - 1]
            run[1][i] = max(run[1][i], run[0][i - 2] + 1)
    return max(run[1])


print(longest_run_one_out([4, 7, 5, 6, 8, 3, 9, 10]))
print(longest_run_one_out([]), longest_run_one_out([5]), longest_run_one_out([2, 2]))
5
0 1 1

The answer is the largest cell in row 1. Here are both rows, and the cell under the 9:

Both rows, and the cell under the 9
run[0]
47568391012123123
run[1]
47568391012234145

The column labels are a[i]. The 4 under the 9 in run[1] comes from run[0] two back: 3 + 1, deleting the 3. run[1] one back gives only 1 + 1 = 2.

It never reads the 4 under the 8, because that run already spent its deletion on the 7.

Check a table you worked out by hand against brute force before you trust it. Your longest_run_brute is that brute force. Here they are on random arrays of 0 to 12 numbers between 0 and 5, full of repeats:

import random

rng = random.Random(1)
for _ in range(2_000):
    a = [rng.randint(0, 5) for _ in range(rng.randint(0, 12))]
    assert longest_run_one_out(a) == longest_run_brute(a), a
print("matched on 2,000 random arrays")
matched on 2,000 random arrays

On 20,000 of them they matched every time. The edges in the first output are right too: [] gives 0, [5] gives 1, and [2, 2] gives 1, because a strictly increasing run can't hold two equal numbers.

The cost is O(n)O(n) time and two rows of nn cells. Each column reads only the two before it, so three columns of two numbers would do.