Maximum sum subarray of size range [ L , R ] | Java program to find Maximum sum subarray of size between L and 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
import java . util . * ; class GFG { static void max_sum_subarray ( List < Integer > arr , int L , int R ) { int n = arr . size ( ) ; int [ ] pre = new int [ n ] ; pre [ 0 ] = arr . get ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { pre [ i ] = pre [ i - 1 ] + arr . get ( i ) ; } List < Integer > s1 = new ArrayList < > ( ) ; s1 . add ( 0 ) ; int ans = Integer . MIN_VALUE ; ans = Math . max ( ans , pre [ L - 1 ] ) ; int flag = 0 ; for ( int i = L ; i < n ; i ++ ) { if ( i - R >= 0 ) { if ( flag == 0 ) { int it = s1 . indexOf ( 0 ) ; s1 . remove ( it ) ; flag = 1 ; } } if ( i - L >= 0 ) s1 . add ( pre [ i - L ] ) ; ans = Math . max ( ans , pre [ i ] - s1 . get ( 0 ) ) ; if ( i - R >= 0 ) { int it = s1 . indexOf ( pre [ i - R ] ) ; s1 . remove ( it ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int L , R ; L = 1 ; R = 3 ; List < Integer > arr = Arrays . asList ( 1 , 2 , 2 , 1 ) ; max_sum_subarray ( arr , L , R ) ; } }