731. Trades With a Fee
A spice trader follows the daily price of saffron in a harbour market. The list prices holds the price of one crate on each day, in order. The trader may hold at most one crate at a time: a crate must be sold before another one is bought, although selling and buying again on the very same day is allowed.
Every sale costs a flat handling charge fee paid to the harbour office. A sale that loses money after the charge is simply never made. Return the largest total profit the trader can collect over all the days, or 0 if no deal is worth making.
Aim for time O(n) and extra space O(1).
Example 1
- Input:
- prices = [14,9,12,20,7,11,25], fee = 3
- Output:
- 23
- Explanation:
Buy at 9 and sell at 20 for 11 - 3 = 8, then buy at 7 and sell at 25 for 18 - 3 = 15, total 23.
Example 2
- Input:
- prices = [30,22,26,24,29], fee = 4
- Output:
- 3
- Explanation:
One deal, buy at 22 and sell at 29, earns 7 - 4 = 3; splitting it into two deals only pays the fee twice.
Example 3
- Input:
- prices = [8,3,3,9], fee = 10
- Output:
- 0
- Explanation:
The best gap is 6 but the fee is 10, so no deal is worth making and the answer is 0.
Constraints
1 ≤ prices.length ≤ 105
1 ≤ prices[i] ≤ 104
0 ≤ fee ≤ 104
The answer fits in a 32-bit signed integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)