// Approach: DP with memoization
// Language: C#
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to find the maximum sum of M non-overlapping subarrays
static int Solve(List<int> arr, int n, int m, int k, int idx, int[,] memo) {
// Base case: If we have selected M subarrays, return 0
if (m == 0) {
return 0;
}
// If the index is beyond the valid range, return a minimum value
if (idx > n - k) {
return int.MinValue;
}
// If the result is already computed, return it from memo
if (memo[idx, m] != -1) {
return memo[idx, m];
}
// Calculate sum of the current subarray of size K
int sum = 0;
for (int i = idx; i < idx + k; i++) {
sum += arr[i];
}
// Option 1: Take the current subarray and move to the next non-overlapping subarray
int take = sum + Solve(arr, n, m - 1, k, idx + k, memo);
// Option 2: Skip the current element and check the next index
int skip = Solve(arr, n, m, k, idx + 1, memo);
// Store the maximum of both choices in memo and return it
return memo[idx, m] = Math.Max(take, skip);
}
// Function to initialize memoization table and call the recursive function
static int MaxSumMSubarrays(List<int> arr, int n, int m, int k) {
int[,] memo = new int[n, m + 1]; // Initialize memo table with -1
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
memo[i, j] = -1;
}
}
return Solve(arr, n, m, k, 0, memo);
}
public static void Main() {
List<int> arr = new List<int> { 2, 10, 7, 18, 5, 33, 0 }; // Input array
int n = arr.Count, m = 3, k = 1; // Define number of subarrays and their size
Console.WriteLine(MaxSumMSubarrays(arr, n, m, k)); // Output the result
}
}