sanhayu546's blog

By sanhayu546, history, 17 months ago, In English

Like we have an array containing 0 and 1 only of length (10^5). we have to do some sort of operation on 1 only like the right shift or left shift by one unit of length so that All 1 in same fashion. And one operation of cost is 1 unit, in minimum cost all 1 in the same fashion.

Example:- 0010101 -> Like in 2 operations we have an array look like this 0001110.

can somebody tell me how to solve this problem?

  • Vote: I like it
  • -5
  • Vote: I do not like it

| Write comment?
»
17 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Find the first and last occurrence of 1's in array . And calculate the number of 0's between them .

»
17 months ago, # |
  Vote: I like it 0 Vote: I do not like it

I'm assuming the problem is the following:

You're given an array of length $$$n \le 10^5$$$, with each element being either $$$0$$$ or $$$1$$$. An move consists of choosing a $$$1$$$, and swapping it with one of its neighbours. Find the least number of moves needed so that all $$$1$$$s form a single connected segment.

Here's how you can solve it: Let's say that the starting position of the final segment is $$$k$$$

. Let the positions of the $$$1$$$s be $$$p_i$$$ for $$$i = 1$$$ to $$$m$$$, where $$$m$$$ is the number of ones in the original array.

Note that you can always make moves so that every move brings a $$$1$$$ closer to its final position (proof left as an exercise). So the minimum number of moves needed is $$$\sum_{i = 1}^m |p_i - k - i + 1|$$$.

Define a new sequence $$$q_i = p_i - i$$$. Then we need to minimize $$$\sum_{i = 1}^m |q_i - (k - 1)|$$$ where $$$k$$$ varies from $$$1$$$ to $$$n - m + 1$$$.

If we remove the restrictions on $$$k$$$, it is well-known that the minimum is achieved when $$$k - 1$$$ is a median of the new sequence.

Now we'll show that any chosen median leads to a valid solution. Indeed, $$$p_i$$$ is an increasing sequence, so $$$p_i > p_{i - 1}$$$ for all $$$i$$$. So $$$q_i = p_i - i > p_{i - 1} - i = q_{i - 1} - 1$$$, and since $$$q_i, q_{i-1}$$$ are integers, $$$q_i \ge q_{i - 1}$$$. So $$$q$$$ is a non-decreasing sequence, and the smallest value is $$$p_1 - 1 \ge 0$$$ and the largest value is $$$p_m - m \le n - m$$$. The median is bounded between these two values, which means that any median also satisfies the bounds, whence we are done.

So the solution becomes very straight-forward: compute any median of the sequence $$$q_i$$$, and the starting position of the first segment and the number of operations needed can be computed from the median conveniently.