Solution to Max-Profit by codility

25 Jan

Question Name: MaxProfit

For this question, we have to travel from the last element to the first one.

21 Replies to “Solution to Max-Profit by codility”

1. Pa says:

Hi Sheng, Thank you so much for sharing your solution! Can you please help me… I am trying to find the start and end index of the maximum-sum-subarray in your solution above. Can you please guide me?

• Sheng says:

You need to add two variables (for begin and end index) and re-write the code in line 14 and 15. If you really understand the solution, it is a easy job.

2. Karol says:

Here is my solution. Python 100/100.

• Sheng says:

From another direction. Thanks for sharing!

3. bhanu prakash says:

C solution, I got 100%

4. Pedro Borges says:

My solution in JAVA

• Sheng says:

Wow! Thanks for sharing another solution!

5. Tom K says:

• Sheng says:

Not a good guess for the initialization value of min_price.

• Tom K says:

Hi Sheng,

Thanks for your website !

Can you explain ? This is the value stated in the exercise.

• Sheng says:

For i == 1, min_price = min(A[i-1], min_price) may get incorrect value if A[i-1] is larger than 200000. Or in another example, when all values in A is larger than 200000, your function will return a wrong answer.

IMO, it is safer to initialize min_price with A[0].

• Tom K says:

Thanks again Sheng,

As stated each element of array A is an integer within the range [0..200,000] so there wouldn’t be such a case.

• Sheng says:

Sorry! I did not notice it. You are absolutely right ðŸ™‚

6. Efthymios says:

I have solved the problem with the following:

However I must admit that this does not work IF the cheapest price is in “the last day”.

• Sheng says:

I cannot agree with you. It’s apparently wrong. Maybe the code is incomplete and you should read the guildlines before posting the code ðŸ™‚

7. Dimuthu says:

100%, 100% Java solution

• Sheng says:

Thanks for your contribution!

8. Jose says:

JS 100% with another point of view

9. M A says:

Yet another variation:
https://codility.com/demo/results/trainingDKETXE-CMH/

thanks for maintaining this blog!

10. Ana says:

Here is my solution in Python:

I can’t see how is this max slice problem – only the first and the last element in the “slice” matter! So, I’m iterating from beginning til the end and pretending that I’m selling on that day. Of course, the best time to buy is the minimum price until that day.

11. A says:

Scala solution: