Let's name our array a
with elements
[a[0], a[1], a[2], ...., a[n]]
The minimum numbers of operations to make a[0]
become 0 is to call foo(0, 1)
or foo(0, -1)
exactly abs(a[0])
times. After this, the array will become
[0, a[1] - a[0], a[2] - a[0], ...., a[n] - a[0]]
Note that this result does not depend on whether a[0]
is positive or negative.
Apply this logic forward, we can summarize the results as
step 1 (as described above)
[0, a[1] - a[0], a[2] - a[0], a[3] - a[0], ...., a[n] - a[0]]
after abs(a[0])
operations
step 2
[0, 0, a[2] - a[0] - (a[1] - a[0]) , a[3] - a[0] - (a[1] - a[0]), ...., a[n] - a[0] - (a[1] - a[0])]
or just
[0, 0, a[2] - a[1] , a[3] - a[1], ...., a[n] - a[1]]
after abs(a[1] - a[0])
operations
step 3
[0, 0, 0 , a[3] - a[1] - (a[2] - a[1]), ...., a[n] - a[1] - (a[2] - a[1])]
or just
[0, 0, 0, a[3] - a[2] ...., a[n] - a[2]]
after abs(a[2] - a[1])
operations
...
step N+1
[0, 0, 0, 0, ..., 0]
after abs(a[n] - a[n-1])
operations
So the minimum number of operations is
abs(a[0]) + abs(a[1] - a[0]) + abs(a[2] - a[1]) + ... + abs(a[n] - a[n-1])
or simply
the sum of the absolute values of the differences
as mentioned by Matt Timmermans