Data Structures & AlgorithmsVery hard
Why does pairing the heaviest remaining person with the lightest one (when they fit together) minimise boats when each boat carries at most two people?
- A. If the heaviest cannot pair with the lightest, it cannot pair with anyone, so it must ride alone; otherwise pairing it with the lightest frees the most capacity for others.
- B. Heavier people always need their own boat.
- C. Pairing the two heaviest is always the best choice.
- D. The lightest person should always ride alone.
Correct answer: A. If the heaviest cannot pair with the lightest, it cannot pair with anyone, so it must ride alone; otherwise pairing it with the lightest frees the most capacity for others.
The heaviest person is the hardest to place, so if any partner fits it is the lightest one, and using that partner leaves the most room for the rest. This exchange argument makes the two-pointer greedy 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
- The minimum number of consecutive deletions to make an array non-decreasing is found by which structure?
- Why is k ≥ n a necessary condition for the residues of n values modulo k to be distinct?
- When counting subsequences 'ace' in a string, why does a DP over the pattern prefixes avoid double counting?
- To count subarrays with equal numbers of even and odd values, which transformation makes the problem a zero-sum subarray problem?
- The function below computes the length of a longest increasing subsequence. python import bisect a = [4, 4, 1, 5, 5, 6, 2, 7] t = [] for x…
- A maximum subarray sum routine is written as follows. python def bestsub(a): cur = best = a[0] for x in a[1:]: cur = max(x, cur + x) best…