
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Max Sum of M Non-Overlapping Subarrays of Size K in C++
Problem statement
Given an array and two numbers M and K. We need to find sum of max M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array size is not multiple of k, then we can take partial last array.
Example
If Given array is = {2, 10, 7, 18, 5, 33, 0}. N = 7, M = 3 and K = 1 then output will be 61 as subset is −
{33, 18, 10}
Algorithm
- We create a presum array, which contains in each index sum of all elements from ‘index‘ to ‘index + K’ in the given array. And size of the sum array will be n+1-k
- Now if we include the subarray of size k, then we can not include any of the elements of that subarray again in any other subarray as it will create overlapping subarrays. So we make recursive call by excluding the k elements of included subarrays
- if we exclude a subarray then we can use the next k-1 elements of that subarray in other subarrays so we will make recursive call by just excluding the first element of that subarray.s
- At last return the max(included sum, excluded sum)
Example
#include <bits/stdc++.h> using namespace std; void calculatePresumArray(int presum[], int arr[], int n, int k) { for (int i = 0; i < k; i++) { presum[0] += arr[i]; } for (int i = 1; i <= n - k; i++) { presum[i] += presum[i-1] + arr[i+k-1] - arr[i- 1]; } } int maxSumMnonOverlappingSubarray(int presum[], int m, int size, int k, int start) { if (m == 0) return 0; if (start > size - 1) return 0; int mx = 0; int includeMax = presum[start] + maxSumMnonOverlappingSubarray(presum, m - 1, size, k, start + k); int excludeMax = maxSumMnonOverlappingSubarray(presum, m, size, k, start + 1); return max(includeMax, excludeMax); } int main() { int arr[] = { 2, 10, 7, 18, 5, 33, 0 }; int n = sizeof(arr)/sizeof(arr[0]); int m = 3, k = 1; int presum[n + 1 - k] = { 0 }; calculatePresumArray(presum, arr, n, k); cout << "Maximum sum = " << maxSumMnonOverlappingSubarray(presum, m, n + 1 - k, k, 0) << endl; return 0; }
When you compile and execute above program. It generates following output −
Output
Maximum sum = 61
Advertisements