Here is the implementation for Red Green Towers (Codeforces 478D). The code implements the recurrence (the formula from the transition) directly. Each step corresponds to part of the formula. To verify your understanding, pick a small example and trace through the code by hand. Write down the value of each variable at each step. This builds intuition that helps when you face new problems. Trace through a small example to see how the DP table fills row by row.
Time complexity: .
Space complexity: where S is total blocks.