Maximum Sum possible by selecting X elements from a Matrix based on given conditions | Python3 program to implement the above approach ; Function to calculate the maximum possible sum by selecting X elements from the Matrix ; Generate prefix sum of the matrix ; Initialize [ , ] dp ; Maximum possible sum by selecting 0 elements from the first i rows ; If a single row is present ; If elements from the current row is not selected ; Iterate over all possible selections from current row ; Return maximum possible sum ; Driver Code
import sys NEW_LINE def maxSum ( grid ) : NEW_LINE INDENT prefsum = [ [ 0 for x in range ( m ) ] for y in range ( m ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for x in range ( m ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT prefsum [ i ] [ x ] = grid [ i ] [ x ] NEW_LINE DEDENT else : NEW_LINE INDENT prefsum [ i ] [ x ] = ( prefsum [ i ] [ x - 1 ] + grid [ i ] [ x ] ) NEW_LINE DEDENT DEDENT DEDENT dp = [ [ - sys . maxsize - 1 for x in range ( X + 1 ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , min ( m , X ) ) : NEW_LINE INDENT dp [ 0 ] [ i ] = ( dp [ 0 ] [ i - 1 ] + grid [ 0 ] [ i - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , X + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE for x in range ( 1 , min ( j , m ) + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - x ] + prefsum [ i ] [ x - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n - 1 ] [ X ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 4 NEW_LINE X = 6 NEW_LINE grid = [ [ 3 , 2 , 6 , 1 ] , [ 1 , 9 , 2 , 4 ] , [ 4 , 1 , 3 , 9 ] , [ 3 , 8 , 2 , 1 ] ] NEW_LINE ans = maxSum ( grid ) NEW_LINE print ( ans ) NEW_LINE DEDENT