Largest sum subarray with at | C ++ program to find largest subarray sum with at - least k elements in it . ; Returns maximum sum of a subarray with at - least k elements . ; maxSum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; We use Kadane 's algorithm to fill maxSum[]  Below code is taken from method 3 of  https:www.geeksforgeeks.org/largest-sum-contiguous-subarray/ ; Sum of first k elements ; Use the concept of sliding window ; Compute sum of k elements ending with a [ i ] . ; Update result if required ; Include maximum sum till [ i - k ] also if it increases overall max . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumWithK ( int a [ ] , int n , int k ) { int maxSum [ n ] ; maxSum [ 0 ] = a [ 0 ] ; int curr_max = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { curr_max = max ( a [ i ] , curr_max + a [ i ] ) ; maxSum [ i ] = curr_max ; } int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += a [ i ] ; int result = sum ; for ( int i = k ; i < n ; i ++ ) { sum = sum + a [ i ] - a [ i - k ] ; result = max ( result , sum ) ; result = max ( result , sum + maxSum [ i - k ] ) ; } return result ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , -10 , -3 } ; int k = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxSumWithK ( a , n , k ) ; return 0 ; }