Largest sum subarray with at | Java 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 method
class Test { static int maxSumWithK ( int a [ ] , int n , int k ) { int maxSum [ ] = new int [ n ] ; maxSum [ 0 ] = a [ 0 ] ; int curr_max = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { curr_max = Math . 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 = Math . max ( result , sum ) ; result = Math . max ( result , sum + maxSum [ i - k ] ) ; } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , - 10 , - 3 } ; int k = 4 ; System . out . println ( maxSumWithK ( arr , arr . length , k ) ) ; ; } }