Given an array and an integer k, find the sum of elements of a subarray containing at least k elements which has the largest sum.
Examples:
Input : arr[] = {-4, -2, 1, -3}, k = 2
Output : -1
Explanation : The sub array is {-2, 1}.Input : arr[] = {1, 1, 1, 1, 1, 1} , k = 2
Output : 6
Explanation : The sub array is {1, 1, 1, 1, 1, 1}
Try It Yourself
Table of Content
[Brute Force] Checking All Possible Subarrays - O(n^2) Time and O(1) Space
We consider every point as starting point and all subarrays of size k or more. We keep track of the maximum sum and return it at the end.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int maxSum(vector<int> &arr, int k) {
int n = arr.size(), res = INT_MIN;
// Iterate over all possible starting points
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// If size of current subarray is k
// or more
if (j - i + 1 >= k) res = max(res, sum);
}
}
return res;
}
int main() {
vector<int> arr = {-4, -2, 1, -3};
int k = 2;
cout << maxSum(arr, k) << endl;
return 0;
}
import java.util.*;
public class GfG {
public static int maxSum(int[] arr, int k) {
int n = arr.length, res = Integer.MIN_VALUE;
// Iterate over all possible starting points
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// If size of current subarray is k
// or more
if (j - i + 1 >= k) res = Math.max(res, sum);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {-4, -2, 1, -3};
int k = 2;
System.out.println(maxSum(arr, k));
}
}
def max_sum(arr, k):
n = len(arr)
res = float('-inf')
# Iterate over all possible starting points
for i in range(n):
sum_ = 0
for j in range(i, n):
sum_ += arr[j]
# If size of current subarray is k
# or more
if j - i + 1 >= k:
res = max(res, sum_)
return res
arr = [-4, -2, 1, -3]
k = 2
print(max_sum(arr, k))
using System;
using System.Linq;
class GfG {
static int MaxSum(int[] arr, int k) {
int n = arr.Length, res = int.MinValue;
// Iterate over all possible starting points
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// If size of current subarray is k
// or more
if (j - i + 1 >= k) res = Math.Max(res, sum);
}
}
return res;
}
static void Main() {
int[] arr = {-4, -2, 1, -3};
int k = 2;
Console.WriteLine(MaxSum(arr, k));
}
}
function maxSum(arr, k) {
let n = arr.length, res = Number.NEGATIVE_INFINITY;
// Iterate over all possible starting points
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = i; j < n; j++) {
sum += arr[j];
// If size of current subarray is k
// or more
if (j - i + 1 >= k) res = Math.max(res, sum);
}
}
return res;
}
// driver code
let arr = [-4, -2, 1, -3];
let k = 2;
console.log(maxSum(arr, k));
Output
-1
[Better Approach] Kadane's Algorithm + Window Sliding - O(n) Time and O(n) Space
- Use Kadane’s algorithm to store the maximum subarray sum ending at each index in maxSum[].
- Find the sum of the first k elements to create the initial window.
- Slide the window through the array, updating the window sum each step.
- Update the answer using either the window sum or the window sum + maxSum[i-k].
#include <iostream>
using namespace std;
int maxSumWithK(vector<int>& arr, int k) {
int n = arr.size();
// maxSum[i] stores maximum sum till index i
vector<int> maxSum(n);
maxSum[0] = arr[0];
// Use Kadane's algorithm to fill maxSum[]
int currMax = arr[0];
for (int i = 1; i < n; i++) {
currMax = max(arr[i], currMax + arr[i]);
maxSum[i] = currMax;
}
// Sum of first k elements
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
// Use sliding window concept
int result = sum;
for (int i = k; i < n; i++) {
// Compute sum of k elements ending with a[i]
sum = sum + arr[i] - arr[i-k];
// Update result if required
result = max(result, sum);
// Include maximum sum till [i-k]
// if it increases overall max
result = max(result, sum + maxSum[i-k]);
}
return result;
}
int main() {
vector<int> arr = {-4, -2, 1, -3};
int k = 2;
cout << maxSumWithK(arr, k);
return 0;
}
import java.util.*;
class GfG {
static int maxSumWithK(int[] arr, int k) {
int n = arr.length;
// maxSum[i] stores maximum sum till index i
int[] maxSum = new int[n];
maxSum[0] = arr[0];
// Use Kadane's algorithm to fill maxSum[]
int currMax = arr[0];
for (int i = 1; i < n; i++) {
currMax = Math.max(arr[i], currMax + arr[i]);
maxSum[i] = currMax;
}
// Sum of first k elements
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
// Use sliding window concept
int result = sum;
for (int i = k; i < n; i++) {
// Compute sum of k elements ending with arr[i]
sum = sum + arr[i] - arr[i - k];
// Update result if required
result = Math.max(result, sum);
// Include maximum sum till [i-k]
// if it increases overall max
result = Math.max(result, sum + maxSum[i - k]);
}
return result;
}
public static void main(String[] args) {
int[] arr = {-4, -2, 1, -3};
int k = 2;
System.out.println(maxSumWithK(arr, k));
}
}
def maxSumWithK(arr, k):
n = len(arr)
# maxSum[i] stores maximum sum till index i
maxSum = [0] * n
maxSum[0] = arr[0]
# Use Kadane's algorithm to fill maxSum[]
currMax = arr[0]
for i in range(1, n):
currMax = max(arr[i], currMax + arr[i])
maxSum[i] = currMax
# Sum of first k elements
sum = 0
for i in range(k):
sum += arr[i]
# Use sliding window concept
result = sum
for i in range(k, n):
# Compute sum of k elements ending with arr[i]
sum = sum + arr[i] - arr[i - k]
# Update result if required
result = max(result, sum)
# Include maximum sum till [i-k]
# if it increases overall max
result = max(result, sum + maxSum[i - k])
return result
if __name__ == "__main__":
arr = [-4, -2, 1, -3]
k = 2
print(maxSumWithK(arr, k))
using System;
class GfG {
static int maxSumWithK(int[] arr, int k) {
int n = arr.Length;
// maxSum[i] stores maximum sum till index i
int[] maxSum = new int[n];
maxSum[0] = arr[0];
// Use Kadane's algorithm to fill maxSum[]
int currMax = arr[0];
for (int i = 1; i < n; i++) {
currMax = Math.Max(arr[i], currMax + arr[i]);
maxSum[i] = currMax;
}
// Sum of first k elements
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
// Use sliding window concept
int result = sum;
for (int i = k; i < n; i++) {
// Compute sum of k elements ending with arr[i]
sum = sum + arr[i] - arr[i - k];
// Update result if required
result = Math.Max(result, sum);
// Include maximum sum till [i-k]
// if it increases overall max
result = Math.Max(result, sum + maxSum[i - k]);
}
return result;
}
static void Main() {
int[] arr = {-4, -2, 1, -3};
int k = 2;
Console.WriteLine(maxSumWithK(arr, k));
}
}
function maxSumWithK(arr, k) {
let n = arr.length;
// maxSum[i] stores maximum sum till index i
let maxSum = new Array(n);
maxSum[0] = arr[0];
// Use Kadane's algorithm to fill maxSum[]
let currMax = arr[0];
for (let i = 1; i < n; i++) {
currMax = Math.max(arr[i], currMax + arr[i]);
maxSum[i] = currMax;
}
// Sum of first k elements
let sum = 0;
for (let i = 0; i < k; i++) {
sum += arr[i];
}
// Use sliding window concept
let result = sum;
for (let i = k; i < n; i++) {
// Compute sum of k elements ending with arr[i]
sum = sum + arr[i] - arr[i - k];
// Update result if required
result = Math.max(result, sum);
// Include maximum sum till [i-k]
// if it increases overall max
result = Math.max(result, sum + maxSum[i - k]);
}
return result;
}
// driver code
let arr = [-4, -2, 1, -3];
let k = 2;
console.log(maxSumWithK(arr, k));
Output
-1
[Optimized] Sliding Window with Kadane’s Optimization- O(n) Time and O(1) Space
We can avoid the use of an extra array in the above approach.
- Keep two sums: one for the current k-sized window and one for elements before it.
- Slide the window through the array, updating the window sum each step.
- Reset the previous sum if it becomes negative (Kadane’s idea).
- Update the maximum sum using either the window sum alone or window sum + previous sum.
#include <iostream>
using namespace std;
int maxSumWithK(vector<int>& arr, int k) {
// Calculate initial sum of
// first k elements (first window)
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
int last = 0;
int j = 0;
int ans = INT_MIN;
ans = max(ans, sum);
// Process rest of the array after first k elements
for (int i = k; i < arr.size(); i++) {
// Add current element to window sum
sum = sum + arr[i];
// Add element at j to 'last' and increment j
last = last + arr[j++];
// Update answer if current window sum is greater
ans = max(ans, sum);
// If sum of elements before window becomes negative
if (last < 0) {
sum = sum - last;
ans = max(ans, sum);
last = 0;
}
}
return ans;
}
int main() {
vector<int> arr = {-4, -2, 1, -3};
int k = 2;
cout << maxSumWithK(arr, k);
return 0;
}
import java.util.*;
class GfG {
static int maxSumWithK(int[] arr, int k) {
// Calculate initial sum of
// first k elements (first window)
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
int last = 0;
int j = 0;
int ans = Integer.MIN_VALUE;
ans = Math.max(ans, sum);
// Process rest of the array after first k elements
for (int i = k; i < arr.length; i++) {
// Add current element to window sum
sum = sum + arr[i];
// Add element at j to 'last' and increment j
last = last + arr[j++];
// Update answer if current window sum is greater
ans = Math.max(ans, sum);
// If sum of elements before window becomes negative
if (last < 0) {
sum = sum - last;
ans = Math.max(ans, sum);
last = 0;
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = {-4, -2, 1, -3};
int k = 2;
System.out.println(maxSumWithK(arr, k));
}
}
def maxSumWithK(arr, k):
# Calculate initial sum of
# first k elements (first window)
sum = 0
for i in range(k):
sum += arr[i]
last = 0
j = 0
ans = float('-inf')
ans = max(ans, sum)
# Process rest of the array after first k elements
for i in range(k, len(arr)):
# Add current element to window sum
sum = sum + arr[i]
# Add element at j to 'last' and increment j
last = last + arr[j]
j += 1
# Update answer if current window sum is greater
ans = max(ans, sum)
# If sum of elements before window becomes negative
if last < 0:
sum = sum - last
ans = max(ans, sum)
last = 0
return ans
if __name__ == "__main__":
arr = [-4, -2, 1, -3]
k = 2
print(maxSumWithK(arr, k))
using System;
class GfG {
static int maxSumWithK(int[] arr, int k) {
// Calculate initial sum of
// first k elements (first window)
int sum = 0;
for (int i = 0; i < k; i++) {
sum += arr[i];
}
int last = 0;
int j = 0;
int ans = int.MinValue;
ans = Math.Max(ans, sum);
// Process rest of the array after first k elements
for (int i = k; i < arr.Length; i++) {
// Add current element to window sum
sum = sum + arr[i];
// Add element at j to 'last' and increment j
last = last + arr[j++];
// Update answer if current window sum is greater
ans = Math.Max(ans, sum);
// If sum of elements before window becomes negative
if (last < 0) {
sum = sum - last;
ans = Math.Max(ans, sum);
last = 0;
}
}
return ans;
}
static void Main() {
int[] arr = {-4, -2, 1, -3};
int k = 2;
Console.WriteLine(maxSumWithK(arr, k));
}
}
function maxSumWithK(arr, k) {
// Calculate initial sum of
// first k elements (first window)
let sum = 0;
for (let i = 0; i < k; i++) {
sum += arr[i];
}
let last = 0;
let j = 0;
let ans = Number.NEGATIVE_INFINITY;
ans = Math.max(ans, sum);
// Process rest of the array after first k elements
for (let i = k; i < arr.length; i++) {
// Add current element to window sum
sum = sum + arr[i];
// Add element at j to 'last' and increment j
last = last + arr[j++];
// Update answer if current window sum is greater
ans = Math.max(ans, sum);
// If sum of elements before window becomes negative
if (last < 0) {
sum = sum - last;
ans = Math.max(ans, sum);
last = 0;
}
}
return ans;
}
// driver code
let arr = [-4, -2, 1, -3];
let k = 2;
console.log(maxSumWithK(arr, k));
Output
-1