Solving the problem of shopping optimization

Is there a solution better than O (n²) to solve the following problem:

On the day I, the unit price is B [i] and they can be sold for S [i] units. If you have 1 unit of cash per day 1, how much can you earn in N days with the restriction that you can never sell shares that you do not have per day?

+3
source share
2 answers

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
    

    , , , , .

0

.

C[i]: cash we can have at end of the day i.
C[i] = max(C[i-1],(S[i]-B[i])*G[i]);

G[i] is unit of good we can afford to buy.
G[i]=floor(C[i-1]/B[i])
0

Source: https://habr.com/ru/post/1773717/


All Articles