Maximum average sum partition of an array | CPP program for maximum average sum partition ; storing prefix sums ; for each i to n storing averages ; Driver code ; int K = 3 ; atmost partitioning size
#include <bits/stdc++.h> NEW_LINE using namespace std ; double largestSumOfAverages ( vector < int > & A , int K ) { int n = A . size ( ) ; double pre_sum [ n + 1 ] ; pre_sum [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) pre_sum [ i + 1 ] = pre_sum [ i ] + A [ i ] ; double dp [ n ] = { 0 } ; double sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = ( pre_sum [ n ] - pre_sum [ i ] ) / ( n - i ) ; for ( int k = 0 ; k < K - 1 ; k ++ ) for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) dp [ i ] = max ( dp [ i ] , ( pre_sum [ j ] - pre_sum [ i ] ) / ( j - i ) + dp [ j ] ) ; return dp [ 0 ] ; } int main ( ) { vector < int > A = { 9 , 1 , 2 , 3 , 9 } ; cout << largestSumOfAverages ( A , K ) << endl ; return 0 ; }