Largest sum subarray with at | 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[] ; 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 code
< ? php function maxSumWithK ( $ a , $ n , $ k ) { $ maxSum [ 0 ] = $ a [ 0 ] ; $ curr_max = $ a [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ curr_max = max ( $ a [ $ i ] , $ curr_max + $ a [ $ i ] ) ; $ maxSum [ $ i ] = $ curr_max ; } $ sum = 0 ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) $ sum += $ a [ $ i ] ; $ result = $ sum ; for ( $ i = $ k ; $ i < $ n ; $ i ++ ) { $ sum = $ sum + $ a [ $ i ] - $ a [ $ i - $ k ] ; $ result = max ( $ result , $ sum ) ; $ result = max ( $ result , $ sum + $ maxSum [ $ i - $ k ] ) ; } return $ result ; } $ a = array ( 1 , 2 , 3 , -10 , -3 ) ; $ k = 4 ; $ n = sizeof ( $ a ) ; echo maxSumWithK ( $ a , $ n , $ k ) ; ? >