| Problem statement | Source code | Tags: Mathematics
This problem pays tribute to 2015 day 19 (unimplemented).
There are three types of neighbor difference : increasing (), decreasing (), and invalid. I can parse the successive differences to this structural representation, which makes subsequent analysis easier.
For part 1, we just need lists that are all Inc or all Dec.
Now we want to delete a single element from the list to make it safe. Obviously there's an solution where we try deleting each element and checking if the result is safe. But we can do better.
For starters, deleting an element can only fix one invalid difference, or two that share an endpoint. So if there are two invalid differences that don't share an endpoint, we can immediately return false. Otherwise, we can try deleting the shared endpoint (or either endpoint if there's just one invalid difference), which removes and , replacing them with (if and ). If or , the resulting list is automatically safe; otherwise, we need to check if is compatible with the remaining differences.
Other than those that are straight Invalid, a difference may also be invalid because it's incompatible with the other differences. Therefore, our first step is to group all differences by type so we can identify the incompatible ones.
Now, there are the following cases: