Largest sum subarray of size K containing consecutive elements | C ++ program for the above approach ; Function to find the largest sum subarray such that it contains K consecutive elements ; Stores sum of subarray having K consecutive elements ; Stores the maximum sum among all subarrays of size K having consecutive elements ; Traverse the array ; Store K elements of one subarray at a time ; Sort the duplicate array in ascending order ; Checks if elements in subarray are consecutive or not ; Traverse the k elements ; If not consecutive , break ; If flag is true update the maximum sum ; Stores the sum of elements of the current subarray ; Update the max_sum ; Reset curr_sum ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( vector < int > A , int N , int K ) { int curr_sum = 0 ; int max_sum = INT_MIN ; for ( int i = 0 ; i < N - K + 1 ; i ++ ) { vector < int > dupl_arr ( A . begin ( ) + i , A . begin ( ) + i + K ) ; sort ( dupl_arr . begin ( ) , dupl_arr . end ( ) ) ; bool flag = true ; for ( int j = 1 ; j < K ; j ++ ) { if ( dupl_arr [ j ] - dupl_arr [ j - 1 ] != 1 ) { flag = false ; break ; } } if ( flag ) { int temp = 0 ; curr_sum = accumulate ( dupl_arr . begin ( ) , dupl_arr . end ( ) , temp ) ; max_sum = max ( max_sum , curr_sum ) ; curr_sum = 0 ; } } return max_sum ; } int main ( ) { vector < int > arr = { 10 , 12 , 9 , 8 , 10 , 15 , 1 , 3 , 2 } ; int K = 3 ; int N = arr . size ( ) ; cout << maximumSum ( arr , N , K ) ; return 0 ; }