Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's an attempt (C++). Basically everytime I track a new top, I try to see if thats the best profit thusfar. I know that the "bottom" must have been discovered earlier. At that point I remember the top, bottom, and the current max profit. If a new bottom is discovered later, its AFTER the current top, so we must reset top and see if a slightly lower "top" can yield better profit.</p> <pre><code>#include &lt;iostream&gt; int main() { double REALLY_BIG_NO = 1e99; double bottom = REALLY_BIG_NO; // arbirtrary large number double currBestBuy = 0.0; double top = 0.0; double currBestSell = 0.0; double profit = 0.0; // array of prices double prices[] = {10.50, 55.39, 109.23, 48.29, 81.59, 105.53, 94.45, 12.24, 152.0, 2, 170.0}; int numPrices = 10;// number of prices for (int i = 0; i &lt; numPrices; ++i) { if (prices[i] &lt; bottom) { bottom = prices[i]; // reset the search on a new bottom top = 0.0; } else if (prices[i] &gt; top) { top = prices[i]; // calculate profit double potentialProfit = (top - bottom); if (potentialProfit &gt; profit &amp;&amp; bottom != REALLY_BIG_NO) { profit = potentialProfit; currBestSell = top; currBestBuy = bottom; } } } std::cout &lt;&lt; "Best Buy: " &lt;&lt; currBestBuy &lt;&lt; "Best Sell: " &lt;&lt; currBestSell &lt;&lt; std::endl; } </code></pre> <p>So far I've played around with a bunch of different input sets, and so far I haven't had any problems... (let me know if you test this and see anything wrong)</p> <p>I highly recommend using <strong>Austin Salonen</strong>'s updated answer to this question and adapting it to your language.</p>
 

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