0

I have an array of integers (both positive and negative). I need to make all the elements of the array zero, by doing the following operation repeatedly. Increasing one element by 1 and decreasing the others by 1 . I need to do this in minimum number of steps (if it is possible to do so). My approach is to sort the integers and then increase the smallest element and decrease all others and keep on doing this until all become zero. But I am not sure, can anyone tell me if there is a seperate correct approach ?

for e.g. if the array is {1,1,3} then according to my approach {2,0,2} -> {1,1,1} -> {2,0,0} -> {1,-1,1} -> {0,0,0}

  • 2
    If your array is {0, 1} how will all elements ever be zero by applying your algorithm? – Eric J. Oct 09 '13 at 20:04
  • I don't get this question. I recommend to add your approach to your question. – Gottlieb Notschnabel Oct 09 '13 at 20:04
  • 1
    More generally, if you have an `n`-element array, your operation decreases the total sum of the array by `n-2`. If the initial total sum is not a positive multiple of `n-2`, there is no solution. – Danica Oct 09 '13 at 20:05
  • but again, Dougal this is not the sufficient condition for not having a solution, for e.g if n=3, then {1,2,3} must have a solution, according to you, but does it ? – Mayank Jha Oct 09 '13 at 20:11
  • What is the purpose of this which means you cannot set all the elements of the array to zero without any other processing? – Andrew Morton Oct 09 '13 at 20:16
  • @AndrewMorton I would assume this is for some kind of homework assignment that he needs to learn the logic of distributing the values over the array – Kierchon Oct 09 '13 at 20:17
  • As other comments have noted, it's obviously not guaranteed that there is always a solution, and the conditions for when there is or isn't may not be entirely clear, but I think that, for a given input, if there is to be a solution, your idea of always increasing the least element and decreasing the others is likely to be the best approach... – twalberg Oct 09 '13 at 21:07

0 Answers0