It can be solved in O (n), for example:
C [i] , i, G [i] , i. , 1 , .
- : C [0] = 1; G [0] = 0.
- 1 n:
- S [i] B [i].
- C [i] = max (C [i - 1], G [i - 1] S [i]) G [i] = max (G [i - 1], C [i - 1]/B [I]).
Python:
from __future__ import division
def max_cash(cash, goods, selling_price, buying_price):
"""Return the maximum amount of cash you can have, if you start with
the given cash and goods, and on day i you can sell goods at
selling_price[i] or buy them at buying_price[i].
Cash and goods are assumed to be arbitrarily divisible.
"""
for sell, buy in zip(selling_price, buying_price):
assert(sell <= buy)
cash, goods = max(cash, goods * sell), max(goods, cash / buy)
return cash
, :
JPvdMerwe , " , ", :
>>> max_cash(0, 1, [2 ** i for i in range(10)], [float('inf')] * 10)
512
- :
>>> max_cash(1, 0, [2, 2, 2], [2, 2, 2])
1
, , , , .