Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum Number of Operations to make an array sorted

I have been trying this problem on spoj, not able to come up with the correct approach. What is the correct algo to solve the problem ?

like image 556
Amol Sharma Avatar asked May 26 '12 03:05

Amol Sharma


People also ask

What is the minimum number of operations required to sort the array in ascending order?

Therefore, the minimum moves required is 2.

What is the minimum number of operations required to make the function value of all arrays equal?

If input array is = {1, 2, 3, 4} then we require minimum 3 operations to make all elements equal. For example, we can make elements 4 by doing 3 additions.

How many steps are required to sort the array?

Therefore, the total number of steps required are 6.

Which sorting needs minimum number of swaps?

Selection Sort requires the minimum number of swaps.


1 Answers

You should find longest consecutive increasing subsequence, which can be done in O(n log n) (by sorting array), after that, the number of changes needed is N - longest consecutive increasing subsequence. Note that by consecutive I mean there order in sorted array.

e.g:

1 7 6 2 5 4 3 => 1-2-3 is longest consecutive increasing subsequence, number of moves needed is 4.

1 6 4 3 5 2 7 => 1-2 or 4-5 or 6-7 is longest consecutive increasing subsequence, note that 1-4-5-7 is longest increasing subsequence but number of moves needed is 5 not 3.

Why this works:

Best algorithm does not changes some of a items places, call biggest subsequence without changes as X, you wont change the position of X items related to each other during operations, so they should be sorted in increasing mode. But because you just allowed to move some items in the first or the last of array, you can't put any item between X items (note that we assumed X is biggest unchanged subsequence during operations), So there should be no gap between X items. so they should be sorted and consecutive in sorted format.

So number of changes needed couldn't be smaller than the N- length of X, but also is not hard to do your job with N-length of X operation.

like image 82
Saeed Amiri Avatar answered Oct 20 '22 10:10

Saeed Amiri