Problem 1 : Longest Stable Subsequence
Consider a list of numbers [a0, a1, ..., an-1]. Our goal is to find the the longest stable subsequence: [ai1, ai2, ..., aik] which is a sub-list of the original list that selects elements at indices i1, i2, ..., ik from the original list such that
1. i1 < i2 < ... < ik;
2. aij+1 - 1 <= aij <= aij+1 + 1. We can also write this as |aij+1 - aij| <= 1. I.e, each element of the subsequence must be within +-1 or equal to the previous element.
3. The length of the subsequence k is maximized.
Example
Consider the list [1, 4, 2, -2, 0, -1, 2, 3]. There are many "stable subsequences":
[1, 0, -1]
[1, 2, 2, 3]
[4, 3]
The longest stable subsequence is [1, 2, 2, 3] of length 4. Note that each element of the subsequence is at most 1 away from the previous element.
The goal of this problem is to formulate a dynamic programming solution to find the length of the longest stable subsequence and the subsequence itself.
A: Write a Recurrence With Base Case
Let n be the length of the original array [a0, ..., an-1]. Define LSSLength(i, aj) to be the length of the longest stable subsequence for the subarray from [ai, ..., an-1] (note that ai is included) with the additional constraint that the first element in the subsequence chosen (let us call it ai_1) must satisfy |ai_1 - aj| <= 1.
Notes
0. 0 <= i <= n. i = n denotes the empty subarray.
1. aj represents a previous choice we have made before encountering the current subproblem. It is made an argument of the recurrence to ensure that the subsequent choice made from [ai, ..., an-1] satisfies |a - aj| <= 1.
2. We will use the special value aj = None to denote that no such element aj has been chosen.
Fill out the missing portion of the recurrence and base cases. We will not grade your answer below. Instead please use it as a guide to complete the code for the recurrence and pass the test cases provided.
LSSLength(i, aj) = { ?? i = n # Base Case when subarray is empty
{ LSSLength(i + 1, aj) i < n and aj != None and |ai - aj| > 1 # We cannot choose a[i], skip it and move right along
{ max(??? + 1, ???) i < n and (aj = None or |ai - aj| <= 1) # Choose maximum of two options: take a[i] or skip a[i]
YOUR ANSWER HERE