You're a buyer/seller and your business is at stake. You need to make profit... Or at least, you need to lose the least amount of money! Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you need to buy one item, then sell it later. Find the best profit you can do.
Input:
A list of prices (integers), of length 2 or more.
Output:
The result of the best buy/sell operation, as an integer.
Example:
Given an array of prices [3, 10, 8, 4], the best profit you could make would be 7 because you buy at 3 first, then sell at 10.
Tests:
max_profit([10, 7, 5, 8, 11, 9])
max_profit([3, 4])
max_profit([9, 9])
max_profit([10, 7, 5, 4, 1])
Good luck!
This challenge comes from wontonst on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (12)
O(n) time and O(1) space: Kadane's algorithm
Nice one, but there are some things that bother me in the code.
You could have replaced the
var
by alet
or aconst
in the first line since you are usinglet
later.You can increase the speed execution of your algorithm by caching the length of the
prices
variables, which is not changing over the course of your iterations.Your variable
maxCurr
lacks a variable declaration keyword: eitherlet
orconst
.Also, you are using the
maxCurr
variable before even declaring it. That does not make sense.I tried to run it but it threw some exceptions, did you run it on your local machine?
Thanks for pointing out, it's a typo. My bad. I have updated the code.
Simple Haskell solution. Uses the property that the maximum difference of two items in a list will be the difference between the maximum and minimum elements.
If max comes before min, then this solution would show a wrong result.
Oh, I misunderstood the challenge. Didn't notice that order requirement.
Don‘t worry... just wanted to point out to you, that you are not done yet. 😬
Keep at it
C++ solution
How is the last output -1? Shouldn't it be 9?
Here I represented the loss with negative number.
For the last case the vector is sorted in descending order. So there is no way user will make any profit. The minimum loss is 1 (i.e. buy the item at price 5 and sell it at price 4).
Remember you have to buy the item first and then sell it.
Here is a short Python recursive solution,
Test Cases,
Elm