Largest sum subarray of size K containing consecutive elements | 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
function maximumSum ( A , N , K ) { let curr_sum = 0 ; let max_sum = Number . MIN_SAFE_INTEGER ; for ( let i = 0 ; i < N - K + 1 ; i ++ ) { let dupl_arr = [ ... A . slice ( i , i + K ) ] ; dupl_arr . sort ( ( a , b ) => a - b ) let flag = true ; for ( let j = 1 ; j < K ; j ++ ) { if ( dupl_arr [ j ] - dupl_arr [ j - 1 ] != 1 ) { flag = false ; break ; } } if ( flag ) { let temp = 0 ; curr_sum = dupl_arr . reduce ( ( acc , cur ) => acc + cur , 0 ) max_sum = Math . max ( max_sum , curr_sum ) ; curr_sum = 0 ; } } return max_sum ; } let arr = [ 10 , 12 , 9 , 8 , 10 , 15 , 1 , 3 , 2 ] ; let K = 3 ; let N = arr . length ; document . write ( maximumSum ( arr , N , K ) ) ;