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 ...
For further actions, you may consider blocking this person and/or reporting abuse
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