Three Array Problems From the Coding Screen
max_profit_single(prices)
- Buy once and sell once later. Return the maximum profit, or 0 if no profitable trade exists.
max_profit_unlimited(prices)
- Any number of non-overlapping buy-sell trades (sell before buying again). Return the maximum total profit.
house_robber(nums)
- Each house holds a non-negative amount; robbing two adjacent houses is not allowed. Return the maximum amount that can be taken. An empty list gives 0.
single_non_duplicate(nums)
nums is sorted and every element appears exactly twice except one, which appears once. Return that element in O(logn) time using binary search.
Hints
- One pass with the running minimum solves the single trade; summing every positive day-to-day rise solves the unlimited case.
- For the single non-duplicate, pairs before the answer start at even indices and pairs after it start at odd indices; compare the middle element with its pair partner.