Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Maximum sum may be found using a dynamic programming algorithm. Scan the array and for each element add its value to the largest sub-sequence sum which is valid (sub-sequence ends with a value not greater than this element).</p> <p>Efficient implementation needs some way to quickly find maximum value in given sub-range. Augmented binary search tree may be used to do it. Fenwick tree is just an efficient implementation of augmented binary search tree. Most common use of Fenwick tree is to find a sum of values in some sub-range. Trivial modification allows to use it to find sub-range maximum (this works because in this particular case values in the Fenwick tree are never decreased).</p> <p>See this Python code for details:</p> <pre class="lang-py prettyprint-override"><code>array = [1, 4, 4, 2, 2, 3, 3, 1] numbers = sorted(set(array)) n = len(numbers) indexes = {numbers[v]:v+1 for v in range(0, n)} n += 1 bit = [0] * n result = 0 for x in array: pos = indexes[x] i = pos maximum = 0 while i != 0: maximum = max(maximum, bit[i]) i = i &amp; (i-1) x += maximum i = pos while i &lt; n: bit[i] = max(bit[i], x) i += i &amp; -i result = max(result, x) print(result) </code></pre> <p><code>indexes</code> dictionary is used to decrease size of Fenwick tree from the largest number in the input array to the array's size. First nested <code>while</code> finds sub-range maximum in Fenwick tree. Second nested <code>while</code> updates Fenwick tree after one of the sums is updated.</p> <p>This code works only for an array of positive numbers. In general case input array should be pre-processed by filtering out all non-positive numbers.</p> <p>Time complexity is O(N log N). Space complexity is O(N).</p>
    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.
    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