Data Structures & AlgorithmsHard
In the 'maximum number of disjoint pairs with sum K' problem, why is a count-based greedy optimal?
- A. Pairs are always disjoint if the values are sorted.
- B. Each value can pair only with its complement K − v, so matching as many copies of each complementary pair as possible is optimal.
- C. The answer is always half the array length.
- D. Greedy works only when K is even.
Correct answer: B. Each value can pair only with its complement K − v, so matching as many copies of each complementary pair as possible is optimal.
Values only pair with complements, so the problem separates into independent groups per complementary class. Matching min(count[v], count[K−v]) pairs in each class is optimal.
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
- To find the longest subarray in which every value appears an even number of times, why can a parity bitmask over values be used with…
- Why is the minimum number of adjacent swaps to make a string palindromic NOT simply half the number of mismatched mirror pairs?
- When repeatedly deleting adjacent pairs of different letters, why does the final length have fixed parity?
- In the 'shortest block to sort so the whole array becomes sorted' problem, why does the block start at the first mismatch with the sorted…
- For an anagram search with a fixed window of length 3, why is a count comparison cheap per step?
- For the 'ramp width' problem (max j − i with A[i] ≤ A[j]), why are only prefix minima and suffix maxima worth considering?