Find maximum sum array of length less than or equal to m
Last Updated :
20 Dec, 2022
Given n arrays of different lengths consisting of integers, the target is to pick atmost one subarray from an array such that the combined length of all picked sub arrays does not become greater than m and also sum of their elements is maximum.(also given that value of n can not be more than 100) Prerequisite: Knapsack Problem Examples :
Input : n = 5, m = 6,
arr[][m] = {{3, 2, 3, 5},
{2, 7, -1},
{2, 8, 10},
{4, 5, 2, 6, 1}
{3, 2, 3, -2}};
Output : Maximum sum can be obtained is 39
Explanation : We are allowed to pick at most one subarray from every array.
We get total sum 39 as ((5) + (7) + (8 + 10) + (4 + 5))
Input : n = 3, m = 4
arr[][m] = {{2, 3, 2},
{3, -1, 7, 10},
{4, 8, 10, -5, 3}};
Output : Maximum sum can be obtained is 35
This problem is similar to Knapsack problem.where you have to either pick an element or leave it. We will have the same strategy here. Given that the total number of elements in these n arrays is at most 10^5. It is also known that m is at most 10^3 and the input arrays can contain negative numbers. First, make a DP table (2D array) of size n * m and then, pre-compute the cumulative sum of an array so that the maximum sum of every length from 1 to n of that array can be easily computed so that for every given array there can be a maximum continuous sum for length k, where k is from 1 to length of the array. In detail, process input arrays one by one. First, compute the maximum sum subarrays of the processed array for all sizes from 1 to length. Then, update our dynamic programming table with these values and we start processing the next array. Algorithm :
- Pick one array from n arrays and start processing it.
- Calculate the maximum contiguous sum for length k, k is from 1 to the length of the array, and save it in the array maxSum.
- Now, fill the DP table by storing the maximum sum possible for every length 0 to m.
- In the last step, we traverse the last row(nth row) of DP table and pick the maximum sum possible and return it.
Below is the implementation of the above approach :
C++
// A Dynamic Programming based C++ program to find
// maximum sum of array of size less than or
// equal to m from given n arrays
#include <bits/stdc++.h>
using namespace std;
/* N and M to define sizes of arr,
dp, current_arr and maxSum */
#define N 105
#define M 1001
// INF to define min value
#define INF -1111111111
// Function to find maximum sum
int maxSum(int arr[][N])
{
// dp array of size N x M
int dp[N][M];
// current_arr of size M
int current_arr[M];
// maxsum of size M
int maxsum[M];
memset(dp, -1, sizeof(dp[0][0]) * N * M);
current_arr[0] = 0;
// if we have 0 elements
// from 0th array
dp[0][0] = 0;
for (int i = 1; i <= 5; i++) {
int len = arr[i - 1][0];
// compute the cumulative sum array
for (int j = 1; j <= len; j++) {
current_arr[j] = arr[i - 1][j];
current_arr[j] += current_arr[j - 1];
maxsum[j] = INF;
}
// calculating the maximum contiguous
// array for every length j, j is from
// 1 to lengtn of the array
for (int j = 1; j <= len && j <= 6; j++)
for (int k = 1; k <= len; k++)
if (j + k - 1 <= len)
maxsum[j] = max(maxsum[j],
current_arr[j + k - 1] -
current_arr[k - 1]);
// every state is depending on
// its previous state
for (int j = 0; j <= 6; j++)
dp[i][j] = dp[i - 1][j];
// computation of dp table similar
// approach as knapsack problem
for (int j = 1; j <= 6; j++)
for (int cur = 1; cur <= j && cur <= len; cur++)
dp[i][j] = max(dp[i][j],
dp[i - 1][j - cur] +
maxsum[cur]);
}
// now we have done processing with
// the last array lets find out
// what is the maximum sum possible
int ans = 0;
for (int i = 0; i <= 6; i++)
ans = max(ans, dp[5][i]);
return ans;
}
// Driver program
int main()
{
// first element of each
// row is the size of that row
int arr[][N] = { { 3, 2, 3, 5 },
{ 2, 7, -1 },
{ 2, 8, 10 },
{ 4, 5, 2, 6, 1 },
{ 3, 2, 3, -2 } };
cout << "Maximum sum can be obtained "
<< "is : " << maxSum(arr) << "\n";
}
Java
// Java program to find maximum sum
// of array of size less than or
// equal to m from given n arrays
import java.io.*;
public class GFG
{
/* N and M to define
sizes of arr,
dp, current_arr
and maxSum */
static int N = 105;
static int M = 1001;
// INF to define
// min value
static int INF = -1111111111;
// Function to find
// maximum sum
static int maxSum(int [][]arr)
{
// dp array of size N x M
int [][]dp = new int[N][M];
// current_arr of size M
int []current_arr = new int[M];
// maxsum of size M
int []maxsum = new int[M];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M ; j++)
dp[i][j] = -1;
}
current_arr[0] = 0;
// if we have 0 elements
// from 0th array
dp[0][0] = 0;
for (int i = 1; i <= 5; i++)
{
int len = arr[i - 1][0];
// compute the cumulative
// sum array
for (int j = 1; j <= len; j++)
{
current_arr[j] = arr[i - 1][j];
current_arr[j] += current_arr[j - 1];
maxsum[j] = INF;
}
// calculating the maximum
// contiguous array for every
// length j, j is from 1 to
// lengtn of the array
for (int j = 1; j <= len && j <= 6; j++)
for (int k = 1; k <= len; k++)
if (j + k - 1 <= len)
maxsum[j] = Math.max(maxsum[j],
current_arr[j + k - 1] -
current_arr[k - 1]);
// every state is depending
// on its previous state
for (int j = 0; j <= 6; j++)
dp[i][j] = dp[i - 1][j];
// computation of dp table
// similar approach as
// knapsack problem
for (int j = 1; j <= 6; j++)
for (int cur = 1; cur <= j &&
cur <= len; cur++)
dp[i][j] = Math.max(dp[i][j],
dp[i - 1][j - cur] +
maxsum[cur]);
}
// now we have done processing
// with the last array lets
// find out what is the maximum
// sum possible
int ans = 0;
for (int i = 0; i <= 6; i++)
ans = Math.max(ans, dp[5][i]);
return ans;
}
// Driver Code
public static void main(String args[])
{
// first element of each
// row is the size of that row
int[][] arr = {
{ 3, 2, 3, 5 },
{ 2, 7, -1 },
{ 2, 8, 10 },
{ 4, 5, 2, 6, 1 },
{ 3, 2, 3, -2 }
};
System.out.println("Maximum sum can be " +
"obtained is : " +
maxSum(arr));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
# A Dynamic Programming based Python3
# program to find maximum sum of array
# of size less than or equal to m from
# given n arrays
# N and M to define sizes of arr,
# dp, current_arr and maxSum
N = 105
M = 1001
# INF to define min value
INF = -1111111111
# Function to find maximum sum
def maxSum(arr):
# dp array of size N x M
dp = [[-1 for x in range(M)]
for y in range(N)]
# current_arr of size M
current_arr = [0] * M
# maxsum of size M
maxsum = [0] * M
current_arr[0] = 0
# If we have 0 elements
# from 0th array
dp[0][0] = 0
for i in range(1, 6):
len = arr[i - 1][0]
# Compute the cumulative sum array
for j in range(1, len + 1):
current_arr[j] = arr[i - 1][j]
current_arr[j] += current_arr[j - 1]
maxsum[j] = INF
# Calculating the maximum contiguous
# array for every length j, j is from
# 1 to lengtn of the array
j = 1
while j <= len and j <= 6:
for k in range(1, len + 1):
if (j + k - 1 <= len):
maxsum[j] = max(maxsum[j],
current_arr[j + k - 1] -
current_arr[k - 1])
j += 1
# Every state is depending on
# its previous state
for j in range(7):
dp[i][j] = dp[i - 1][j]
# computation of dp table similar
# approach as knapsack problem
for j in range(1, 7):
cur = 1
while cur <= j and cur <= len:
dp[i][j] = max(dp[i][j],
dp[i - 1][j - cur] +
maxsum[cur])
cur += 1
# Now we have done processing with
# the last array lets find out
# what is the maximum sum possible
ans = 0
for i in range(7):
ans = max(ans, dp[5][i])
return ans
# Driver code
if __name__ == "__main__":
# First element of each
# row is the size of that row
arr = [ [ 3, 2, 3, 5 ],
[ 2, 7, -1 ],
[ 2, 8, 10 ],
[ 4, 5, 2, 6, 1 ],
[ 3, 2, 3, -2 ] ]
print("Maximum sum can be obtained",
"is : ", maxSum(arr))
# This code is contributed by chitranayal
C#
// C# program to find maximum sum
// of array of size less than or
// equal to m from given n arrays
using System;
class GFG
{
/* N and M to define
sizes of arr,
dp, current_arr
and maxSum */
static int N = 105;
static int M = 1001;
// INF to define
// min value
static int INF = -1111111111;
// Function to find
// maximum sum
static int maxSum(int [][]arr)
{
// dp array of size N x M
int [,]dp = new int[N, M];
// current_arr of size M
int []current_arr = new int[M];
// maxsum of size M
int []maxsum = new int[M];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M ; j++)
dp[i, j] = -1;
}
current_arr[0] = 0;
// if we have 0 elements
// from 0th array
dp[0, 0] = 0;
for (int i = 1; i <= 5; i++)
{
int len = arr[i - 1][0];
// compute the cumulative
// sum array
for (int j = 1; j <= len; j++)
{
current_arr[j] = arr[i - 1][j];
current_arr[j] += current_arr[j - 1];
maxsum[j] = INF;
}
// calculating the maximum
// contiguous array for every
// length j, j is from 1 to
// lengtn of the array
for (int j = 1; j <= len && j <= 6; j++)
for (int k = 1; k <= len; k++)
if (j + k - 1 <= len)
maxsum[j] = Math.Max(maxsum[j],
current_arr[j + k - 1] -
current_arr[k - 1]);
// every state is depending
// on its previous state
for (int j = 0; j <= 6; j++)
dp[i, j] = dp[i - 1, j];
// computation of dp table
// similar approach as
// knapsack problem
for (int j = 1; j <= 6; j++)
for (int cur = 1; cur <= j &&
cur <= len; cur++)
dp[i, j] = Math.Max(dp[i, j],
dp[i - 1, j - cur] +
maxsum[cur]);
}
// now we have done processing
// with the last array lets
// find out what is the maximum
// sum possible
int ans = 0;
for (int i = 0; i <= 6; i++)
ans = Math.Max(ans, dp[5, i]);
return ans;
}
// Driver Code
static void Main()
{
// first element of each
// row is the size of that row
int[][] arr = new int[][]
{
new int[]{ 3, 2, 3, 5 },
new int[]{ 2, 7, -1 },
new int[]{ 2, 8, 10 },
new int[]{ 4, 5, 2, 6, 1 },
new int[]{ 3, 2, 3, -2 }
};
Console.Write ("Maximum sum can be " +
"obtained is : " +
maxSum(arr) + "\n");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
JavaScript
// Javascript program to find maximum sum
// of array of size less than or
// equal to m from given n arrays
/* N and M to define
sizes of arr,
dp, current_arr
and maxSum */
let N = 105;
let M = 1001;
// INF to define
// min value
let INF = -1111111111;
// Function to find
// maximum sum
function maxSum(arr)
{
// dp array of size N x M
let dp = new Array(N);
for(let i = 0;i<N;i++){
dp[i] = new Array(M);
}
// current_arr of size M
let current_arr = new Array(M);
// maxsum of size M
let maxsum = new Array(M);
for (let i = 0; i < N; i++)
{
for (let j = 0; j < M ; j++){
dp[i][j] = -1;
}
}
current_arr[0] = 0;
// if we have 0 elements
// from 0th array
dp[0][0] = 0;
for (let i = 1; i <= 5; i++)
{
let len = arr[i - 1][0];
// compute the cumulative
// sum array
for (let j = 1; j <= len; j++)
{
current_arr[j] = arr[i - 1][j];
current_arr[j] += current_arr[j - 1];
maxsum[j] = INF;
}
// calculating the maximum
// contiguous array for every
// length j, j is from 1 to
// lengtn of the array
for (let j = 1; j <= len && j <= 6; j++)
for (let k = 1; k <= len; k++)
if (j + k - 1 <= len)
maxsum[j] = Math.max(maxsum[j],
current_arr[j + k - 1] -
current_arr[k - 1]);
// every state is depending
// on its previous state
for (let j = 0; j <= 6; j++)
dp[i][j] = dp[i - 1][j];
// computation of dp table
// similar approach as
// knapsack problem
for (let j = 1; j <= 6; j++)
for (let cur = 1; cur <= j &&
cur <= len; cur++)
dp[i][j] = Math.max(dp[i][j],
dp[i - 1][j - cur] +
maxsum[cur]);
}
// now we have done processing
// with the last array lets
// find out what is the maximum
// sum possible
let ans = 0;
for (let i = 0; i <= 6; i++)
ans = Math.max(ans, dp[5][i]);
return ans;
}
// first element of each
// row is the size of that row
let arr = [
[ 3, 2, 3, 5 ],
[ 2, 7, -1 ],
[ 2, 8, 10 ],
[ 4, 5, 2, 6, 1 ],
[ 3, 2, 3, -2 ]
];
console.log("Maximum sum can be " + "obtained is : " + maxSum(arr));
// This code is contributed by aadityaburujwale.
OutputMaximum sum can be obtained is : 39
Time complexity : O(m^2 n)
Auxiliary Space: O(n*m)
Similar Reads
Maximum length L such that the sum of all subarrays of length L is less than K Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) =
8 min read
Minimum operations to make sum at least M from given two Arrays Given arrays A[] and B[] of size N and integer M, the task is to find out the minimum operations required to collect a sum of at least M by performing the following operations any number of times. Either choosing the first element of A[] or the first element of B[] remove that element from the front
11 min read
Maximize sum of chosen Array elements with value at most M Given an array arr[] of N positive numbers and an integer M. The task is to maximize the value of M by adding array elements when arr[i] ⤠M. Note: Any array element can be added at most once. Examples: Input: arr[] = {3, 9, 19, 5, 21}, M = 10Output: 67Explanation: One way to getthe value isM > 3
4 min read
Count of subsequences in an array with sum less than or equal to X Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
13 min read
Find the maximum range [L,R] whose sum is divisible by M Given an array arr[] consisting of positive numbers, the task is to find the maximum range [L, R] whose sum is divisible by M. If there is no range present return -1. Examples: Input: arr[] = {3, 7, 5, 2, 5, 10}, M = 3 Output: 1 3 Explanation: Sum of numbers from 1 to 3 is 3+7+5 which is 15. Input :
8 min read
Program to find sum of elements in a given 2D array Given a 2D array of order M * N, the task is to find out the sum of elements of the matrix. Examples: Input: array[2][2] = {{1, 2}, {3, 4}};Output: 10 Input: array[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};Output: 136 Approach: The sum of each element of the 2D array ca
12 min read
Find the maximum sum after dividing array A into M Subarrays Given a sorted array A[] of size N and an integer M. You need to divide the array A[] into M non-empty consecutive subarray (1 ? M ? N) of any size such that each element is present in exactly one of the M-subarray. After dividing the array A[] into M subarrays you need to calculate the sum [max(i)
10 min read
Maximize total set bits of elements in N sized Array with sum M Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
8 min read
Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M Given an array arr[] of size N consisting of only the first M natural numbers, the task is to find the minimum length of the subarray that is required to be replaced such that the frequency of array elements is N / M. Note: N is a multiple of M. Examples: Input: M = 3, arr[] = {1, 1, 1, 1, 2, 3}Outp
10 min read
Sum of elements in an array with frequencies greater than or equal to that element Given an array arr[] of N integers. The task is to find the sum of the elements which have frequencies greater than or equal to that element in the array. Examples: Input: arr[] = {2, 1, 1, 2, 1, 6} Output: 3 The elements in the array are {2, 1, 6} Where, 2 appear 2 times which is greater than equal
9 min read