
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Maximum Size Subarray Sum Equals k in C++
- Minimum Size Subarray Sum 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
- Maximum Unique Element in every subarray of size K in c++
- Find maximum average subarray of k length in C++
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Maximum contiguous sum of subarray in JavaScript
- Maximum subarray sum by flipping signs of at most K array elements in C++
- C++ program to find maximum of each k sized contiguous subarray
- Using Kadane’s algorithm to find maximum sum of subarray in JavaScript
- Program to find maximum absolute sum of any subarray in Python
- Product of all Subsequences of size K except the minimum and maximum Elements in C++
- Find Maximum XOR value of a sub-array of size k in C++
- Find Maximum Sum Strictly Increasing Subarray in C++

Advertisements