Iterate over all possible selections from current row
for ( int x = 1 ; x <= Math . min ( j , m ) ; x ++ ) { dp [ i ] [ j ] = Math . max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - x ] + prefsum [ i ] [ x - 1 ] ) ; } } }