Largest sum subarray of size K containing consecutive elements | Python3 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
import sys NEW_LINE def maximumSum ( A , N , K ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT dupl_arr = A [ i : i + K ] NEW_LINE dupl_arr . sort ( ) NEW_LINE flag = True NEW_LINE for j in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( dupl_arr [ j ] - dupl_arr [ j - 1 ] != 1 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT temp = 0 NEW_LINE curr_sum = temp NEW_LINE curr_sum = sum ( dupl_arr ) NEW_LINE max_sum = max ( max_sum , curr_sum ) NEW_LINE curr_sum = 0 NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 12 , 9 , 8 , 10 , 15 , 1 , 3 , 2 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( maximumSum ( arr , N , K ) ) NEW_LINE DEDENT