Data Structures & AlgorithmsHardGATE CS · TCS NQT
A routine builds a list t: for each x in a, it appends x to t only if x is larger than the last element of t (otherwise it skips x), and it returns len(t). For the array [5, 1, 2, 3, 4], what value does the routine return?
- A. 4
- B. 2
- C. 1
- D. 5
Correct answer: C. 1
The routine commits to the first element 5 and never reconsiders it, so it returns 1. The true LIS of [5, 1, 2, 3, 4] is 1, 2, 3, 4 with length 4. Greedy appending fails because it can lock out a better start.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Items as (weight, value) are [(2, 3), (3, 4), (1, 1)]. The 0/1 knapsack table dp[c] for capacities c = 0..6 is built correctly by scanning…
- Intervals [(1, 6), (2, 4), (3, 9), (5, 7), (8, 10), (4, 5)] are given as closed ranges. You must remove the fewest intervals so that no…
- How many non-empty contiguous subarrays of [1, -1, 2, 0, 1, 3, -2, 1] have a sum equal to their length (number of elements)? Transform…
- Choose any subset of the positions of [4, -2, 7, 3, 9, 1, -5, 8, 2] (possibly empty) so that every two chosen positions are at least 3…
- Assertion (A): Dynamic programming over subsets for TSP needs exponential time in the number of cities. Reason (R): The number of subsets…
- Assertion (A): Kadane's algorithm can be used to find the maximum subarray sum in O(n) time. Reason (R): It keeps the best sum ending at…