When you compute , you need and for various k. Both of those are shorter ranges than .
So you must solve shorter ranges first. The outer loop iterates over length (from ), and the inner loop iterates over starting positions. This is different from most DP where you iterate over indices directly. Getting the loop order wrong means you'll access uncomputed values.