Consider an array that contains positive integers. A subarray of is defined to be a sequence of array locations with consecutive indices.
The code snippet given below has been written to compute the length of the longest subarray of that contains at most two distinct integers. The code has two missing expressions labelled and .
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 -th iteration, the value of is the length of the longest subarray ending with that contains all equal values, and is the length of the longest subarray ending with that contains at most two distinct values.)
View worked solution
Answer: B
To find the correct expressions for (P) and (Q), we can analyze the state of the variables at the -th iteration using the hint provided:
len1is the length of the longest contiguous subarray ending at containing identical elements.len2is the length of the longest subarray ending at containing at most two distinct elements.
Case 1: When X[i] == second
Since is equal to second, it is different from first (which is ). This means the contiguous block of identical elements ending at is broken, and a new contiguous block of identical elements starts at . Thus, its length len1 must be reset to .
Case 2: When X[i] is a new element (the else block)
Since is different from both first and second, the new subarray ending at with at most two distinct elements can only contain and the contiguous block of first elements immediately preceding it. The length of this preceding contiguous block is len1. Including the new element , the new length len2 becomes:
Thus, the correct option is B.
Free practice · Your answers on this page are not saved.
