How can we find the maximum sum of a non-decreasing sub-sequence in an array using fenwick tree? For example we have 1 4 4 2 2 3 3 1, here the maximum sum of a non-decreasing sub-sequence is 11 (1 2 2 3 3).
相关问题
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
- Newtonsoft DeserializeXNode expands internal array
相关文章
- Numpy matrix of coordinates
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- PHP: Can an array have an array as a key in a key-
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Accessing an array element when returning from a f
- How can I convert a PHP function's parameter l
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).
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).
See this Python code for details:
indexes
dictionary is used to decrease size of Fenwick tree from the largest number in the input array to the array's size. First nestedwhile
finds sub-range maximum in Fenwick tree. Second nestedwhile
updates Fenwick tree after one of the sums is updated.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.
Time complexity is O(N log N). Space complexity is O(N).