Data Structures & AlgorithmsHard
Why does the two-transaction stock problem split the array at a point and solve each side independently?
- A. Two transactions can always be merged into one.
- B. With at most two transactions, the two buy-sell pairs can be separated by a single cut, so the best answer is the best split of the one-transaction profits.
- C. The optimal two transactions are always the first and last days.
- D. Splitting is unnecessary because each transaction is independent of the other.
Correct answer: B. With at most two transactions, the two buy-sell pairs can be separated by a single cut, so the best answer is the best split of the one-transaction profits.
Any two non-overlapping transactions can be separated by a cut day, so the answer is the maximum over cuts of the best single-transaction profit on each side. A running minimum computes each side in linear time.
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
- When the maximum and minimum must end at the two extremes by adjacent swaps, why can their costs interact?
- Why does 'maximum number of disjoint zero-sum blocks' use an interval DP over prefixes rather than a greedy scan?
- To count subarrays of length at least 2 with equal odd and even counts, why is the length-1 case excluded?
- Why is the minimum over all rotations of a permutation's inversion count achieved by a specific rotation that can be found in linear time?
- When covering all distinct values of an array with a subarray, why does a sliding window track counts rather than a single flag?
- Why does the sum-of-suffix-maxima total equal a simple right-to-left scan?