3
votes

The cost of a bond on each day is given in array prices of length n, and I need to find the maximum profit that I can make by buying and selling in exactly k transactions (buying and selling, in that order. not in the same day. but I can sell and then buy in the same day).

I tried (Python):

prices = [3, 1, 10]
n = len(prices)

def aux(i, j):
    if j == n - 1 or i == 0:
        return 0
    s = [(prices[j + t] - prices[j]) + aux(i - 1, j + t)
         for t in range(1, n - j)]
    return max(aux(i, j + 1), max(s)) if s else aux(i, j + 1)

def max_profit(k):
    return aux(k, 0)

But for the given array in the code, and with k=2 I get 9 when It should be (1 - 3) + (10 - 1) = 7. It seem to get the maximum profit for at most k transactions and not exactly k.

How can it be fixed?

1
Can you also provide an Input and Output, example so that I can work on itzenwraight
@zenwraight In the code sample there is prices = [3, 1, 10] and I wrote what should be when you call it with k=2po1son
Surely the maximum profit is made by buying at 1 and selling at 10 and should be 9 ? Or is there something you are not telling us ?High Performance Mark

1 Answers

0
votes

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.