There is an array of numbers between 0 and 6 (base 7). For example {0 4 6 2 2 0 3 1}. Its maximum length can be 501 elements. Each step we can subtract a number from any number of elements. All of the elements must be adjacent (form a continuous sub-array). The number subtracted from all of the elements must be the same.
If an element (let's call it A) after subtraction doesn't fit in the range of 0 to 6, then A becomes A modulo 7. For example after subtracting 3 from the whole array {0 4 6 2 2 0 3 1}
, we would get
{4 1 3 6 6 4 0 5}
.
The task is to find the smallest amount of steps necessary to get an array with just zeros.
For example for the array {0 4 6 2 2 0 3 1}
it would take 4 steps:
{0 4 6 2 2 0 3 1}
subtract 2 from elements with indexes 2-4
{0 4 4 0 0 0 3 1}
subtract 4 from elements with indexes 1 and 2
{0 0 0 0 0 0 3 1}
subtract 3 from the second to last element
{0 0 0 0 0 0 0 1}
subtract 1 from the last element
{0 0 0 0 0 0 0 0}
First of all finding the solution using brute force is not possible, as for an array of 501 numbers there are 126 505 506 possible first steps. (6x(1x501 + 2x500 + 3x499 + 4x498 +...+ 501x1) = 6x21084251 = 126505506). There would be a lot more possibilities if we include the steps following the first one.
I noticed we can remove an element if it has the same number next to it.
So the array {0 4 6 2 2 0 3 1}
becomes {0 4 6 2 0 3 1}
. This should simplify the problem.
I've tried dividing the array into sections using zeros as the dividers.
So for the array {0 4 6 2 0 3 1}
we could consider two separate arrays: {4 6 2}
and {3 1}
.
I thought I could find the answers for those arrays and add them together for the final answer.
But I discovered arrays for which this approach doesn't work.
For example, for the array {3 2 1 0 1 2 3}
this approach would yield the answer 3 + 3 = 6 while it should be 4 steps:
{3 2 1 0 1 2 3}
subtract 3 from the whole array
{0 6 5 4 5 6 0}
subtract 6 for indexes 1 to 5
{0 0 6 5 6 0 0}
subtract 6 for indexes 2 to 4
{0 0 0 6 0 0 0}
subtract 6 from the middle element
{0 0 0 0 0 0 0}
Another approach I tried was looking for pairs of the same number and dividing the array accordingly.
For example the array: {0 3 1 5 3 5 6 2 1 5 1}
would divide into three arrays {3 1 5 3}
and {5 6 2 1 5}
and {6}
.
This would allow me to shorten a sub-array by two elements in just one step:
{3 1 5 3} {5 6 2 1 5} {6}
subtract from the first subarray
{0 5 2 0} {5 6 2 1 5} {6}
subtract from the second subarray
{0 5 2 0} {0 1 4 3 0} {6}
remove zeroes on the sides -> {5 2} {1 4 3} {6}
But I couldn't find a final solution using this approach. Also I don't know how to check whether it always would return the best answer.