a tough dp, several WAs. There must be a better algo