Solve stock and banana problems
Company: Apple
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates algorithmic problem-solving skills related to array processing, optimization under constraints, and reasoning about performance trade-offs by presenting a maximum single-transaction stock profit problem and a minimum banana-eating speed problem.
Part 1: Maximum Single-Transaction Stock Profit
Constraints
- 0 <= len(prices) <= 100000
- 0 <= prices[i] <= 100000
Examples
Input: ([7, 1, 5, 3, 6, 4],)
Expected Output: 5
Explanation: Buy at 1 and sell later at 6 for a profit of 5.
Input: ([7, 6, 4, 3, 1],)
Expected Output: 0
Explanation: Prices keep decreasing, so no profitable sell is possible.
Hints
- As you move from left to right, what is the only information you need from previous days to evaluate selling today?
- Keep track of the lowest price seen so far, then compare each current price against it.
Part 2: Minimum Banana-Eating Speed
Constraints
- 1 <= len(piles) <= 10000
- 1 <= piles[i] <= 1000000000
- len(piles) <= h <= 1000000000
Examples
Input: ([3, 6, 7, 11], 8)
Expected Output: 4
Explanation: At speed 4, the hours needed are 1 + 2 + 2 + 3 = 8, which fits exactly.
Input: ([30, 11, 23, 4, 20], 5)
Expected Output: 30
Explanation: There are 5 piles and only 5 hours, so each pile must be finished in one hour. The largest pile requires speed 30.
Hints
- For a fixed speed `k`, compute the total hours by summing the ceiling of `pile / k` for each pile.
- If speed `k` is fast enough, then any speed greater than `k` is also fast enough. That monotonic property suggests binary search.