Блог пользователя Muhammad_mhs

Автор Muhammad_mhs, история, 4 года назад, По-английски

Stick Lengths In this problem , sort the array and I have to make all sticks size equal to array[n/2] ( n/2 = median ) then answer should be the minimum. But why I choose median index. Can anyone explain, Please ? Thanks in advance.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

These kind of problems get solved by finding the medium element. Assume the stick lengths to be points on the X0 axis. We need to move all points into a single one while having the shortest possible distance sum of moving.

That single point is at a location where left of it are the same number of points as right of it. Because if we got more points on one of the sides we could move the point into that direction by one unit, which would decrease the sum of distances on that side by the number of elements. And increases the sum on the other side by the number of elements on the other side.

So, to find the point with minimum sum we need to move it in direction of the half with more points until both halfes are same.

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +4 Проголосовать: не нравится

You can think about it following way : If you move to the left or to the right from n/2, try to see the change in cost.

Spoiler

What about moving to the left.

Spoiler

Similarly to the right.