Maximum average sum partition of an array | javascript program for maximum average sum partition ; storing prefix sums ; for each i to n storing averages ; Driver code ; var K = 3 ; atmost partitioning size
function largestSumOfAverages ( A , K ) { var n = A . length ; var pre_sum = Array ( n + 1 ) . fill ( - 1 ) ; pre_sum [ 0 ] = 0 ; for ( var i = 0 ; i < n ; i ++ ) pre_sum [ i + 1 ] = pre_sum [ i ] + A [ i ] ; var dp = Array ( n ) . fill ( - 1 ) ; var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) dp [ i ] = ( pre_sum [ n ] - pre_sum [ i ] ) / ( n - i ) ; for ( k = 0 ; k < K - 1 ; k ++ ) for ( i = 0 ; i < n ; i ++ ) for ( j = i + 1 ; j < n ; j ++ ) dp [ i ] = Math . max ( dp [ i ] , ( pre_sum [ j ] - pre_sum [ i ] ) / ( j - i ) + dp [ j ] ) ; return dp [ 0 ] ; } var A = [ 9 , 1 , 2 , 3 , 9 ] ; document . write ( largestSumOfAverages ( A , K ) ) ;