Maximum sum subarray of size range [ L , R ] | function to find Maximum sum subarray of size between L and R ; calculating prefix sum ; maintain 0 for initial values of i upto R Once i = R , then we need to erase that 0 from our multiset as our first index of subarray cannot be 0 anymore . ; we maintain flag to counter if that initial 0 was erased from set or not . ; erase 0 from multiset once i = b ; insert pre [ i - L ] ; find minimum value in multiset . ; erase pre [ i - R ] ; Driver code
function max_sum_subarray ( arr , L , R ) { let n = arr . length ; let pre = new Array ( n ) ; pre [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { pre [ i ] = pre [ i - 1 ] + arr [ i ] ; } let s1 = [ ] s1 . push ( 0 ) ; let ans = Number . MIN_VALUE ; ans = Math . max ( ans , pre [ L - 1 ] ) ; let flag = 0 ; for ( let i = L ; i < n ; i ++ ) { if ( i - R >= 0 ) { if ( flag == 0 ) { let it = s1 . indexOf ( 0 ) ; s1 . splice ( it , 1 ) ; flag = 1 ; } } if ( i - L >= 0 ) s1 . push ( pre [ i - L ] ) ; ans = Math . max ( ans , pre [ i ] - s1 [ 0 ] ) ; if ( i - R >= 0 ) { let it = s1 . indexOf ( pre [ i - R ] ) ; s1 . splice ( it , 1 ) ; } } document . write ( ans ) ; } let L , R ; L = 1 ; R = 3 ; let arr = [ 1 , 2 , 2 , 1 ] ; max_sum_subarray ( arr , L , R ) ;