I’ve been trying some code challanges recently and I’m currently stuck in the challange referenced in the title of this post. challange
I thought I found a viable way to solve it, however, my code doesn’t get past test number 5.
I’ve been testing it with different lists combinations with different values and, while it is not the best code out there, it seems to work just fine everytime I test it. I just can’t figure out what’s wrong with it.
// Consider the case:
print(max_profit_days([150, 11, 60, 25, 150, 75, 31, 120]))
// Your code returns (1, 0)
// It should return (1, 4)
// Sell day can't be an earlier day than buy day
I fixed it with the following code. (I added an if statement that test if the selling price has more than one ocurrance and if so, it will get the first ocurrance after the buy day)
Whereas it now returns (1, 4), it still fails test number five of the challange.
A couple of observations and then I will share my thoughts about the 5th test.
while count < 7 // It is possible that the test lists may have days less/more than a week, so perhaps choice of 7 might not be suitable for some shorter/longer test lists. If you want to use a while loop, perhaps consider the length of stock_prices in deciding upon a suitable condition.
Have a look at the documentation for the index method. It has optional arguments which can help you search through slices of the list and yet return an index relative to the whole list. For example:
x = [1, 2, 4, 6, 3, 7, 1, 6, 7]
print(x.index(6)) // Output: 3
print(x.index(6, 4)) // Output: 7
// Searches for the number 6 in the slice of the list from
// index 4 (inclusive) onward.
// The index returned is relative to the beginning of the whole list,
// so the number 6 is at index 7.
Using the optional start argument of index can make your code simpler. But, if you want to persist with your current approach, that is fine as well.
Now about the 5th test. I played around with the challenge and passed 4/5 tests. Then, I tried different things and passed 5/5 tests. From what I understand, the sell date can’t be the same as the buy date. The prices are listed at the opening of each day. So, if you have bought a stock on the first day, you must wait at least till the next day to sell the stock. What that means is:
print(max_profit_days([17, 17))
// Should output (0, 1)
// Your code outputs (0, 0)
print(max_profit_days([17, 16))
// Should output (0, 1)
// Your code outputs (1, 1)
// Even though it is a loss, it is the best we can do.
So, the bottom line for the 5th test is that the buy date and sell date can’t be the same. The sell date can’t be less or equal to the buy date. Once I made this modification to my code, 5/5 tests were passed.