After processing all h levels, dp[h][j] tells you: "how many ways to build the full tower using exactly j red blocks." But not every j is valid.
You need: j≤r and S−j≤g. The final answer is the sum of all valid dp[h][j]:
answer=∑0≤j≤rS−j≤gdp[h][j](mod109+7)
Iterating j from 0 to S and checking both constraints takes O(S) time after the DP is filled.