Maximum profit by buying and selling a share exactly k times

拥有回忆 提交于 2019-12-06 02:22:37

Your stopping condition shouldn't allow the function to finish successfully if k is not totally consumed. Try something like this

if i == 0:
    return 0
elif j == n - 1:
    return -2**30

In the first case, when i == 0, that means that k is totally consumed and we can't proceed anymore. so we can't win or lose anymore, thus return 0.

Now, in the second condition, assuming that the first one wasn't true, that means that we reached the end of the array without totally consuming k. Hence, this is not a valid answer. To mark an answer as invalid, we have to give it a really bad value so it would be rejected anyway compared to any other valid answer.

Since this is a maximization problem, a bad value means a very small number, so when we maximize with other answers, it'll always be discarded.

-2**30 is a pretty close value to the minimum value of an integer, so this should be small enough. I'm making the assumption that all your operations will fit in a 32-bit integer, hence this should be a small enough value. If this is not true you have to pick a small value, enough to be less that the smallest value that you could ever get in a valid answer. You can pick -2**60 or even -2**100 since this is Python and you don't have to worry about overflow issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!