Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong><code>O(n)</code> solution:</strong></p> <p><strong>High-level:</strong></p> <p>The basic idea is to repeatedly merge any element <code>e</code> smaller than both its neighbours <code>ns</code> and <code>nl</code> with its smallest neighbour <code>ns</code>. This produces the minimal cost because both the cost and result of merging is <code>max(a[i],a[i+1])</code>, which means no merge can make an element smaller than it currently is, thus the cheapest possible merge for <code>e</code> is with <code>ns</code>, and that merge can't increase the cost of any other possible merges.</p> <p>This can be done with a one pass algorithm by keeping a stack of elements from our array in decreasing order. We compare the current element to both its neighbours (one being the top of the stack) and perform appropriate merges until we're done.</p> <p><strong>Pseudo-code:</strong></p> <pre class="lang-java prettyprint-override"><code>stack = empty for pos = 0 to length // stack.top &gt; arr[pos] is implicitly true because of the previous iteration of the loop if stack.top &gt; arr[pos] &gt; arr[pos+1] stack.push(arr[pos]) else if stack.top &gt; arr[pos+1] &gt; arr[pos] merge(arr[pos], arr[pos+1]) else while arr[pos+1] &gt; stack.top &gt; arr[pos] merge(arr[pos], stack.pop) </code></pre> <p><strong>Java code:</strong></p> <pre class="lang-java prettyprint-override"><code>Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;(); int cost = 0; int arr[] = {10,1,2,3,4,5}; for (int pos = 0; pos &lt; arr.length; pos++) if (pos &lt; arr.length-1 &amp;&amp; (stack.empty() || stack.peek() &gt;= arr[pos+1])) if (arr[pos] &gt; arr[pos+1]) stack.push(arr[pos]); else cost += arr[pos+1]; // merge pos and pos+1 else { int last = Integer.MAX_VALUE; // required otherwise a merge may be missed while (!stack.empty() &amp;&amp; (pos == arr.length-1 || stack.peek() &lt; arr[pos+1])) { last = stack.peek(); cost += stack.pop(); // merge stack.pop() and pos or the last popped item } if (last != Integer.MAX_VALUE) { int costTemp = Integer.MAX_VALUE; if (!stack.empty()) costTemp = stack.peek(); if (pos != arr.length-1) costTemp = Math.min(arr[pos+1], costTemp); cost += costTemp; } } System.out.println(cost); </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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