Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It can be solved in O(<em>n</em>), like this:</p> <p>C[<em>i</em>] represents the maximum cash you can hold at the end of day <em>i</em>, and G[<em>i</em>] represents the maximum amount of goods you can hold at the end of day <em>i</em>. I'm going to suppose you start out with 1 unit of cash and no goods, but the algorithm will work for other initial conditions.</p> <ul> <li>Initialize: C[0] = 1; G[0] = 0. </li> <li>Repeat for <em>i</em> from 1 to <em>n</em>:</li> <li>Let the selling price on day <em>i</em> be S[<em>i</em>] and the buying price B[<em>i</em>].</li> <li>Set C[<em>i</em>] = max(C[<em>i</em> − 1], G[<em>i</em> − 1]S[<em>i</em>]) and G[<em>i</em>] = max(G[<em>i</em> − 1], C[<em>i</em> − 1]/B[<em>i</em>]).</li> </ul> <p>Here's an implementation in Python:</p> <pre class="lang-py prettyprint-override"><code>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 &lt;= buy) cash, goods = max(cash, goods * sell), max(goods, cash / buy) return cash </code></pre> <p>Let's check this on some of the alleged counter-examples raised in comments:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/4128487/solving-buying-selling-optimization-problem/4128648#comment4463612_4128648">JPvdMerwe</a> suggests that this case "breaks all greedy algorithms I can think of", but the algorithm above works fine:</p> <pre><code>&gt;&gt;&gt; max_cash(0, 1, [2 ** i for i in range(10)], [float('inf')] * 10) 512 </code></pre></li> <li><p><a href="https://stackoverflow.com/questions/4128487/solving-buying-selling-optimization-problem/4128648#comment4464004_4128648">Keegan Carruthers-Smith</a> suggests this counter-example:</p> <pre><code>&gt;&gt;&gt; max_cash(1, 0, [2, 2, 2], [2, 2, 2]) 1 </code></pre> <p>which is unsurprising since the selling price is always the same as the buying price, and so no profit can be made, and so you can't possibly end up with more cash than you started with.</p></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload