Skip to content

Beta · Data may be lost.Your data may be reset or lost.

GateBrew
← GATE CSE 2024 Set 2
Questions

Q32

MCQ2 marks, −0.67Algorithms

Consider an array X\mathrm{X} that contains n\mathrm{n} positive integers. A subarray of X\mathrm{X} is defined to be a sequence of array locations with consecutive indices. The C\mathrm{C} code snippet given below has been written to compute the length of the longest subarray of X\mathrm{X} that contains at most two distinct integers. The code has two missing expressions labelled (P)\text{(P)} and (Q)\text{(Q)}.

int first=0, second=0, len1=0, len2=0, maxlen=0;
for (int i=0; i < n; i++) {
    if (X[i] == first) {
        len2++; len1++;
    } else if (X[i] == second) {
        len2++;
        len1 = (P);
        second = first;
    } else {
        len2 = (Q);
        len1 = 1; second = first;
    }
    if (len2 > maxlen) {
        maxlen = len2;
    }
    first = X[i];
}

Which one of the following options gives the CORRECT missing expressions? (Hint: At the end of the ii-th iteration, the value of len1len 1 is the length of the longest subarray ending with X[i]\mathrm{X}[i] that contains all equal values, and len2len 2 is the length of the longest subarray ending with X[i]\mathrm{X}[i] that contains at most two distinct values.)

Sign in to save attempts.

The solution is hidden while you attempt this question. It opens once you check or show the answer.