A nice backtracking problem! Initially I had some difficulty understanding the problem statement. So, I’ll try to break down the problem statement and illustrate with the sample test cases.

We’re given two integers, a surplus $s$ and a deficit $d$. Each of the $12$ months had either a surplus or a deficit, but we don’t which months or how many months. But another useful information is given - the $8$ postings, each of consecutive $5$ months during a year, all reported a deficit. What does this mean?

How many combinations of $5$ consecutive months in a year are there? See the following:

\[ 1. \textrm{[January, February, March, April, May]} \] \[ 2. \textrm{[February, March, April, May, June]} \] \[ 3. \textrm{[March, April, May, June, July]} \] \[ \cdots \] \[ 8. \textrm{[August, September, October, November, December]} \]

So, in total there are $8$ combinations and the problem states these all of these combinations reported a deficit, i.e. assigning either a surplus or deficit to each of the $5$ months will yield in a deficit for that particular $5$ months period.

As we don’t know which of the months have surpluses and which of them have deficits, we don’t have any other option but to try them all. How many possible combinations there are? Each month has two possible options - either a surplus or a deficit, and there are $12$ months. So, there are a total of $2^{12} = 4096 - 1$ combinations.

But all of them are not valid. After assigning a surplus or a deficit to each month, we have to check if the given constraint is respected. If not, then we’ll prune the search space.

There’s one significant optimization to prune the search space. We’ve stated before that for each month, we could either assign it a surplus or a deficit. Which will we assign first? Remember the problem asks if a surplus is possible, and if possible then we have to maximize it. So we’ll start by assigning a surplus to each month and we’ll assign a deficit only if the above constraint is violated. In this way, once we’ve found a valid answer, it will be the maximum. Because after the answer is updated for the first time, any other answer could be found only by assigning deficits to the months, which will result in a worse answer.

Here’s the implementation in C++: