// C# program for
// the above approach
using System;
class GFG{
// Function to select m elements
// having maximum sum
public static int mElementsWithMaxSum(int[,] matrix,
int M, int block,
int[,] dp)
{
// Base case
if (block == matrix.GetLength(0))
return 0;
// If precomputed subproblem occurred
if (dp[block, M] != -1)
return dp[block, M];
// Either skip the current row
int ans = mElementsWithMaxSum(matrix, M,
block + 1, dp);
// Iterate through all the possible
// segments of current row
for (int i = 0;
i < GetRow(matrix, block).Length; i++)
{
for (int j = i;
j < GetRow(matrix, block).Length; j++)
{
// Check if it is possible to select
// elements from i to j
if (j - i + 1 <= M)
{
// Compute the sum of i to j as
// calculated
ans = Math.Max(ans, matrix[block, j] -
((i - 1) >= 0 ?
matrix[block, i - 1] : 0) +
mElementsWithMaxSum(matrix,
M - j + i - 1,
block + 1, dp));
}
}
}
// Store the computed answer and return
return dp[block, M] = ans;
}
// Function to precompute the prefix sum
// for every row of the matrix
public static void preComputing(int[,] matrix,
int N)
{
// Preprocessing to calculate sum from i to j
for (int i = 0; i < N; i++)
{
for (int j = 0;
j < GetRow(matrix, i).Length; j++)
{
matrix[i, j] = (j > 0 ? matrix[i, j - 1] : 0) +
matrix[i, j];
}
}
}
// Utility function to select
// m elements having maximum sum
public static void mElementsWithMaxSumUtil(int[,] matrix,
int M, int N)
{
// Preprocessing step
preComputing(matrix, N);
// Initialize dp array with -1
int [,]dp = new int[N + 5, M + 5];
for(int i = 0; i < N + 5; i++)
{
for (int j = 0; j < M + 5; j++)
{
dp[i, j] = -1;
}
}
// Stores maximum sum of M elements
int sum = mElementsWithMaxSum(matrix, M,
0, dp);
// Print the sum
Console.Write(sum);
}
public static int[] GetRow(int[,] matrix,
int row)
{
var rowLength = matrix.GetLength(1);
var rowVector = new int[rowLength];
for (var i = 0; i < rowLength; i++)
rowVector[i] = matrix[row, i];
return rowVector;
}
// Driver Code
public static void Main(String []args)
{
// Given N
int N = 3;
// Given M
int M = 4;
// Given matrix
int[,] matrix = {{2, 3, 5},
{-1, 7,0},
{8, 10, 0}};
// Function Call
mElementsWithMaxSumUtil(matrix, M, N);
}
}
// This code is contributed by Princi Singh