配列 A = [5,1,7,2,3] を考えてみましょう
すべての連続部分配列 = { [5]、[1]、[7]、[2]、[3]、[5,1]、[1,7]、[7,2]、[2,3]、[ 5,1,7]、[1,7,2]、[7,2,3]、[5,1,7,2]、[1,7,2,3]、[5,1,7、 2,3] }
上記のセットのすべての配列をその中の最大要素に置き換えます。
セットは次のようになります: { [5], [1], [7], [2], [3], [5], [7], [7], [3], [7], [7] , [7], [7], [7], [7] }
頻度情報: [5] -> 2、[1] -> 1、[7] -> 9、[2] -> 1、[3] -> 2
私の目標は、上記の周波数情報を見つけることです。
私のアプローチ:
最初にペア (x,y) のリストを作成します。x は A の要素で、そのインデックスは y です。
リスト : [ (5,1), (1,2), (7,3), (2,4), (3,5) ]
最初の要素に関して降順でリストを並べ替えます。さて、
リスト : [ (7,3), (5,1), (3,5), (2,4), (1,2) ]
アルゴリズム:
def f( array, first_index, last_index):
->select an element from LIST starting from left which
is not marked as visited and (first_index <= element.second <=
last_index)
->calculate frequency info of element in tuple as (element.secondvalue-first_index+1) + (element.secondvalue-first_index+1)*(last_index - element.second_value)
->Mark above element as visited
->Recursively solve f( array, first_index,element.secondvalue-1 ),f( array,element.secondvalue+1,last_index)
適切なベースケースを簡単に設定できます。
時間計算量:O(n*n)
上記のアルゴリズムを使用するために多くのことを試みましたが、時間の複雑さを改善できませんでした。どうすれば改善できますか?ヒント、アプローチをいただければ幸いです。