
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
Find Maximum or Minimum Sum of a Subarray of Size K in C++
In this problem, we are given an array arr[] and a number k. Our task is to Find the maximum (or minimum) sum of a subarray of size k.
Let’s take an example to understand the problem,
Input: arr[] = {55, 43, 12, 76, 89, 25, 99} , k = 2
Output: 165
Explanation:
The subarray of size 2 has sum = 76 + 89 = 165
Solution Approach
A simple approach to solve the problem is by finding all k sized subarrays and then return the sum with maximum value.
Another Approach is using the sliding window, we will find the sum of k sized subarrayes. For this, the next k sized subarray, we will subtract the last index element and add the next index element.
And then return the subarray sum with the maximum value.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int findMaxSumSubarray(int arr[], int n, int k) { if (n < k) { cout << "Invalid"; return -1; } int maxSum = 0; for (int i=0; i<k; i++) maxSum += arr[i]; int curr_sum = maxSum; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; maxSum = max(maxSum, curr_sum); } return maxSum; } int main() { int arr[] = {55, 43, 12, 76, 89, 25, 99}; int n = sizeof(arr)/sizeof(arr[0]); int k = 2; cout<<"The sum of subarray with max sum of size "<<k<<" is "<<findMaxSumSubarray(arr, n, k); return 0; }
Output
The sum of subarray with max sum of size 2 is 165
Advertisements