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.
Input: ([],)
Expected Output: 0
Explanation: With no prices, no transaction can be made.
Input: ([5],)
Expected Output: 0
Explanation: With only one day, you cannot both buy and sell later.
Input: ([2, 4, 1],)
Expected Output: 2
Explanation: Buy at 2 and sell at 4 for a profit of 2.
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.
Input: ([30, 11, 23, 4, 20], 6)
Expected Output: 23
Explanation: Speed 23 works in 6 hours, but any smaller speed takes more than 6 hours.
Input: ([1], 1)
Expected Output: 1
Explanation: One banana in one hour requires a minimum speed of 1.
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.