Maximum length L such that the sum of all subarrays of length L is less than K | Function to return the maximum sum in a subarray of size k ; k must be greater ; Compute sum of first window of size k ; Compute sums of remaining windows by removing first element of previous window and adding last element of current window . ; Function to return the length of subarray Sum of all the subarray of this length is less than or equal to K ; Binary search from l to r as all the array elements are positive so that the maximum subarray sum is monotonically increasing ; Check if the subarray sum is greater than K or not ; Update the maximum length ; Driver code
def maxSum ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT res = 0 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT res += arr [ i ] ; NEW_LINE DEDENT curr_sum = res ; NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - k ] ; NEW_LINE res = max ( res , curr_sum ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def solve ( arr , n , k ) : NEW_LINE INDENT max_len = 0 ; l = 0 ; r = n ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) // 2 ; NEW_LINE if ( maxSum ( arr , n , m ) > k ) : NEW_LINE INDENT r = m - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 ; NEW_LINE max_len = m ; NEW_LINE DEDENT DEDENT return max_len ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 10 ; NEW_LINE print ( solve ( arr , n , k ) ) ; NEW_LINE DEDENT