Find maximum sum array of length less than or equal to m in C++

C++Server Side ProgrammingProgramming

In the problem, we are given n arrays of different length. Our task is to Find the maximum sum array of length less than or equal to m.

We need to find sub-arrays from the arrays to maximise the sum and make the length of all subarrays combined equal to m.

Let’s take an example to understand the problem,

Input

n = 3, m = 4
arrOfArr[][] = {
   {5, 2, -1, 4, -3}
   {3, -2, 1, 6}
   {-2, 0, 5}
}

Output

20

Explanation

SubArrays are {5, 4}, {6}, {5},
length = 2 + 1 + 1 = 4
Sum = 5 + 4 + 6 + 5 = 20

Solution Approach

The problem can be solved using a dynamic programming approach. We will create a DP array and compute the cumulative array sums of length k which varies from 0 to m.

In the DP array, store the maximum array sum for all lengths from 0 to m for each array in the 2D DP. Then return the maximum sum which will be at the last row of the array.

Program to illustrate the working of our solution,

Example

#include <bits/stdc++.h>
using namespace std;
#define N 5
int findMax(int a, int b){
   if(a > b)
      return a;
      return b;
}
int findMaxSumArray(int arr[][N], int M) {
   int DP[N][M];
   int sumArray[M];
   int sum[M];
   memset(DP, -1, sizeof(DP[0][0]) * N * M);
   sumArray[0] = 0;
   DP[0][0] = 0;
   for (int i = 1; i <= 5; i++) {
      int len = arr[i - 1][0];
      for (int j = 1; j <= len; j++) {
         sumArray[j] = arr[i - 1][j];
         sumArray[j] += sumArray[j - 1];
         sum[j] = -100;
      }
      for (int j = 1; j <= len && j <= 6; j++)
         for (int k = 1; k <= len; k++)
            if (j + k - 1 <= len)
               sum[j] = findMax(sum[j], sumArray[j + k - 1] - sumArray[k - 1]);
         for (int j = 0; j <= 6; j++)
            DP[i][j] = DP[i - 1][j];
         for (int j = 1; j <= 6; j++)
            for (int cur = 1; cur <= j && cur <= len; cur++)
               DP[i][j] = findMax(DP[i][j], DP[i - 1][j - cur] + sum[cur]);
   }
   int maxSum = 0;
   for (int i = 0; i <= 6; i++)
      maxSum = findMax(maxSum, DP[5][i]);
      return maxSum;
}
int main() {
   int arr[][N] = { { 3, 2, -1, 6 },
   { 2, 7, -1 },
   { 3, 2, 2, -4 } };
   int m = 4;
   cout<<"Maximum sum array of length less than or equal to "<<m<<" : "<<findMaxSumArray(arr, m);
}

Output

Maximum sum array of length less than or equal to 4 : 15
raja
Published on 12-Mar-2021 06:15:53
Advertisements