I came across a problem in stackoverflow. The problem gives you an array and a value 'K'. You can move an element to right at any position, but you can't move it more than K positions left. Find the optimal ordering on which number of inversions is minimum, e.g. array 3,1,2
has 2
inversions. For K=1
, solution array is: 1,3,2
.
I had a greedy algorithm for this problem, but can't prove its correctness (though I'm pretty sure about its correctness):
iterate the array from left to right.
For each position i
we consider a subarray from i to i+k
. Then we find the minimum valued element on this subarray and insert this element at the beginning of the subarray and right shift the rest of elements.
Now, go to position i+1
and do the same.
for example:
given array = 5 3 4 7 8 2 1 0 and K = 2
this algorithm gets the solution array as this:
3 4 5 2 1 0 7 8
minimum inversion value = 12
this is just a naive version of algorithm which we can make faster as O(nlogn).
But is this correct at all? Help is greatly appreciated.