Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum number of operation of specific function

I got this question from an company's interview but I could not find the minimum (according to me minimum operations are highest number or lowest number) but I'm not sure. Please can someone help me? Thanks

The question is :-

Given an array and an operation foo(index, value),

  • the value can be either 1 or -1,
  • if foo(index, value) is called, it will add value to all elements from index till end of the array

Find minimum number of operation to make all array elements 0.

like image 210
Abc Avatar asked Jun 03 '18 12:06

Abc


2 Answers

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

like image 173
gchen Avatar answered Oct 27 '22 14:10

gchen


Consider the difference between each element and the preceding element. For the first element use the difference from 0, i.e., its value.

Now, calling foo(index, value) will change exactly one of these differences, either increasing it or decreasing it by 1.

Since the result you want has all of these differences equal to 0, and foo() can only change one of them by 1, the minimum number of times you need to call foo() is the sum of the absolute values of the differences.

like image 38
Matt Timmermans Avatar answered Oct 27 '22 14:10

Matt Timmermans