DP solution for 369 (runs in ~10s).