Problem 341011 · easy · Phase 03 Linear Management & Searching

Trade Every Uptick

greedy · iteration · adjacent comparison

prices[i] is the price of one crate of coffee on day i. You may hold at most one crate at a time, and you may buy and sell as often as you like, even selling and buying again on the same day. Return the largest total profit you can make. If no profit is possible, return 0.

Examples

Input:  prices = [3, 1, 4, 1, 5]
Output: 7
Explanation: Buy at 1, sell at 4 (+3); buy at 1, sell at 5 (+4).
Input:  prices = [5, 4, 3]
Output: 0

Constraints

  • 0 <= len(prices) <= 10**5, 0 <= prices[i] <= 10**6.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • See that any profitable trade decomposes into day-to-day rises
  • Collect all positive differences in one pass
Starting Python…