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.

27 Replies to “Solution to Max-Profit by codility

  1. 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?

    • 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. Here is my solution. Python 100/100.

  3. C solution, I got 100%

  4. My solution in JAVA

  5. 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”.

    • I cannot agree with you. It’s apparently wrong. Maybe the code is incomplete and you should read the guildlines before posting the code 🙂

  6. 100%, 100% Java solution

  7. JS 100% with another point of view

  8. Yet another variation:

    thanks for maintaining this blog!

  9. 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.

  10. Scala solution:

  11. C# with some functional fun

  12. 100% javascript solution:

  13. Python 100/100; Just find profit/loss first and then apply max slice algorithm. Much easier to understand the code, in my opinion.

  14. I would like to thank Sheng for his contribution. I admire your unique approach to solving codility tests. Here is my C# solution where I basically keep track of smallest value and calculate profit using it

  15. My approach:

Leave a Reply

Your email address will not be published. Required fields are marked *

Please put your code into a <pre>YOUR CODE</pre> section. Thanks and Happy Coding!