We score a solution by counting the total number of paired bases. Thus, attempting to maximize the score that maximizes the total number of bonds between bases.
Consider an RNA sequence
whose elements are taken from the set
. Let us imagine we have an optimal solution to the subproblem of folding
to
, and an optimal solution for folding
to
. Now, to align
to
, we have two options:
- Leave
unpaired, and keep the structure of
to
. The score for this alignment will be equal to the score of the alignment of
to
, as no new base pairs were created.
- Pair
with
, where
. The score for this alignment will be the score of the base pairing, plus the score of the best alignment of
to
and
to
.
Consider an RNA sequence
of length
such that
.
Construct an
matrix
. Initialize
such that


for
.
will contain the maximum score for the subsequence
. Now, fill in entries of
up and to the right, so that

where 
After this step, we have a matrix
where
represents the optimal score of the folding of
.
To determine the structure of the folded RNA by traceback, we first create an empty list of pairs
. We initialize with
. Then, we follow one of three scenarios.
- If
, the procedure stops.
- If
, then set
and continue.
- Otherwise, for all
, if
and
are complementary and
, append
to
, then traceback both with
and
.
When the traceback finishes,
contains all of the paired bases.