Spices between ports
- O(n) · Medium
- Full plan
- Python
- JavaScript
- lists
- loops
- comparisons
Problem
"Cheap first, dear later, never the other way", Captain Brea tells her crew. Her ship calls at one port after another, and at each one she knows the price of a sack of cinnamon. On the whole voyage she buys one sack, at some port, and sells it at one of the ports that come later.
Write a function that takes the list of prices, in the order the ship visits the ports, and returns a whole number: the largest profit she can make, which is the selling price minus the buying price.
With 9, 4, 7, 2 and 5, the best move is to buy at 4 and sell at 7, or buy at 2 and sell at 5: a profit of 3. You cannot buy at 2 and sell at 9, because by the time you reach the 2, the port with the 9 is behind you. Prices are positive whole numbers. If no purchase makes a profit, because prices only go down or stay the same, or because there are fewer than two ports, she buys nothing and you return 0.
Examples
The example
[9, 4, 7, 2, 5] → 3
The best deal spans the whole voyage
[3, 8, 2, 6, 10, 1] → 8
The cheapest comes after the dearest
[12, 5, 8, 1] → 3
Prices only go down
[10, 8, 5, 3] → 0
Prices only go up
[2, 4, 9] → 7
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def best_profit(prices):
passJavaScript
function bestProfit(prices) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.