Data Structures & AlgorithmsHardCodeforces Div2 C · TCS NQT
From the numbers [1, 9, 4, 7, 3, 12, 8, 5], form as many DISJOINT pairs as possible where the two numbers in each pair differ by at most 2 (each number is used at most once). What is the maximum number of pairs?
- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: A. 3
Sort and pair neighbours greedily: the closest pairs in sorted order are the ones that can be paired, and skipping an element that cannot pair with its successor is safe. Taking the first available partner in input order can block a better pairing.
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
- A circular binary string is "1101001010". A swap exchanges any two characters. What is the minimum number of swaps needed so that all 1s…
- Each row and each column of a 4 × 4 matrix is sorted in increasing order: [[1, 5, 9, 12], [2, 6, 10, 15], [3, 7, 11, 16], [4, 8, 13, 20]]…
- Choose a subsequence of [3, 8, 1, 9, 2, 7] (keeping order, possibly any length ≥ 1). Its alternating sum is the first chosen element minus…
- What is the length of the longest contiguous subarray of [4, 7, 2, 9, 6, 3, 8, 10, 5] in which the parity of consecutive elements…
- Choose a subsequence of [5, -2, 7, 1, -3, 6, 4] in which any two consecutive CHOSEN indices differ by at most 2 positions (by index). A…
- How many ways can "abcabcdaab" be cut into a non-empty left part and a non-empty right part so that the two parts contain the same number…