Open In App

Largest sum subarray of size at least k

Last Updated : 15 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array and an integer k, the task is to 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} 

[Naive Approach] – O(n^2) Time and O(1) Space

The idea is simple, 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.

C++
#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;
}
Java
import java.util.*;

public class Main {
    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));
    }
}
Python
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))
C#
using System;
using System.Linq;

class Program {
    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));
    }
}
JavaScript
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;
}

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

The idea is to find a subarray with at least k elements having the maximum possible sum, by combining Kadane’s algorithm with a sliding window approach. We first compute the maximum sum achievable up to each index using Kadane’s algorithm, then use a sliding window of size k to find sums of consecutive k elements, and for each window we also consider including the maximum sum achievable before that window to potentially get a larger subarray sum.

Step by step approach:

  1. Initialize maxSum[] array using Kadane’s algorithm to store maximum sum achievable up to each index.
  2. Calculate initial sum of first k elements as starting window.
  3. Slide the window one element at a time, updating window sum by adding new element and removing first element.
  4. For each window position, consider two possibilities: either take just the window sum, or window sum plus maxSum up to index (i-k).
  5. Keep track of maximum sum seen so far as the result.
  6. Return the final maximum sum that represents the largest subarray sum with at least k elements.

Below is the implementation of above approach: 

C++
// C++ program to find largest subarray sum with
// at-least k elements in it.
#include <bits/stdc++.h>
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;
}
Java
// Java program to find largest subarray sum with
// at-least k elements in it.
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));
    }
}
Python
# Python program to find largest subarray sum with
# at-least k elements in it.

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))
C#
// C# program to find largest subarray sum with
// at-least k elements in it.
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));
    }
}
JavaScript
// JavaScript program to find largest subarray sum with
// at-least k elements in it.

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;
}

let arr = [-4, -2, 1, -3];
let k = 2;
console.log(maxSumWithK(arr, k));

Output
-1

Time Complexity: O(n)
Auxiliary Space: O(n)

[Optimized and Expected] – O(n) Time and O(1) Space

The idea is to maintain two sliding counters – one for calculating the sum of the current k-sized window, and another for tracking the sum of elements before the window (like Kadane’s algorithm). As we slide through the array, we update both sums, and whenever the sum of elements before the window becomes negative, we discard it since it won’t contribute positively to our overall sum. The maximum sum with at least k elements will either be just the k-sized window sum or the window sum plus some positive sum of elements before it.

C++
// C++ program to find largest subarray sum with
// at-least k elements in it.
#include <bits/stdc++.h>
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;
}
Java
// Java program to find largest subarray sum with
// at-least k elements in it.
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));
    }
}
Python
# Python program to find largest subarray sum with
# at-least k elements in it.

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))
C#
// C# program to find largest subarray sum with
// at-least k elements in it.
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));
    }
}
JavaScript
// JavaScript program to find largest subarray sum with
// at-least k elements in it.

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;
}

let arr = [-4, -2, 1, -3];
let k = 2;
console.log(maxSumWithK(arr, k));

Output
-1

Time Complexity: O(n)
Auxiliary Space: O(1)



Next Article

Similar Reads