Question

Let AA be an array containing integer values. The distance of AA is defined as the minimum number of elements in AA that must be replaced with another integer so that the resulting array is sorted in non-decreasing order. The distance of the array [2,5,3,1,4,2,6][2, 5, 3, 1, 4, 2, 6] is ___________

Official answer and solution
Official answer
3
From
Official GATE 2024 answer key

Solution

Find the length LL of the longest non-decreasing subsequence of AA and subtract LL from the array length n=7n = 7.

To minimize the number of elements replaced to make A=[2,5,3,1,4,2,6]A = [2, 5, 3, 1, 4, 2, 6] sorted in non-decreasing order, we maximize the number of elements kept unchanged, which must form a non-decreasing subsequence of AA.

Inspecting A=[2,5,3,1,4,2,6]A = [2, 5, 3, 1, 4, 2, 6]:

  • The longest non-decreasing subsequence has length L=4L = 4: specifically [2,3,4,6][2, 3, 4, 6] (at indices 1,3,5,71, 3, 5, 7).
  • Keeping [2,,3,,4,,6][2, _, 3, _, 4, _, 6] fixed, we can replace the remaining 7−4=37 - 4 = 3 elements (5,1,25, 1, 2) with integers 2,3,42, 3, 4 respectively to obtain the non-decreasing array [2,2,3,3,4,4,6][2, 2, 3, 3, 4, 4, 6].
  • No non-decreasing subsequence of length 55 exists.

Therefore, the distance of the array is 7−4=37 - 4 = 3.

Final answer

3

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
Question
35 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.