Reverse a subarray of the given array to minimize the sum of elements at even position | Java implementation to reverse a subarray of the given array to minimize the sum of elements at even position ; Function that will give the max negative value ; Check for count greater than 0 as we require only negative solution ; Function to print the minimum sum ; Taking sum of only even index elements ; Initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; Get the max negative value ; Driver code
import java . util . * ; class GFG { static final int N = 5 ; static int after_rev ( Vector < Integer > v ) { int mini = 0 , count = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { count += v . get ( i ) ; if ( count > 0 ) count = 0 ; if ( mini > count ) mini = count ; } return mini ; } static void print ( int arr [ ] ) { int sum = 0 ; for ( int i = 0 ; i < N ; i += 2 ) sum += arr [ i ] ; Vector < Integer > v1 , v2 ; v1 = new Vector < Integer > ( ) ; v2 = new Vector < Integer > ( ) ; for ( int i = 0 ; i + 1 < N ; i += 2 ) v1 . add ( arr [ i + 1 ] - arr [ i ] ) ; for ( int i = 1 ; i + 1 < N ; i += 2 ) v2 . add ( arr [ i ] - arr [ i + 1 ] ) ; int change = Math . min ( after_rev ( v1 ) , after_rev ( v2 ) ) ; if ( change < 0 ) sum += change ; System . out . print ( sum + "NEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 4 , 3 , 0 } ; print ( arr ) ; } }