

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Maximum Size Subarray Sum Equals k in C++
- Minimum Size Subarray Sum in C++
- Maximum Unique Element in every subarray of size K in c++
- Find maximum average subarray of k length in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- C++ program to find maximum of each k sized contiguous subarray
- Find Maximum XOR value of a sub-array of size k in C++
- Find Maximum Sum Strictly Increasing Subarray in C++
- Maximum product of subsequence of size k in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Product of all Subsequences of size K except the minimum and maximum Elements in C++
- Subarray Sum Equals K in C++
- Program to find minimum largest sum of k sublists in C++
- Maximum contiguous sum of subarray in JavaScript
Advertisements