text: Delete odd and even numbers at alternate step such that sum of remaining elements is minimized | C ++ implementation of the approach ; Function to find the minimized sum ; If more odd elements ; Sort the elements ; Left - over elements ; Find the sum of leftover elements ; Return the sum ; If more even elements ; Sort the elements ; Left - over elements ; Find the sum of leftover elements ; Return the sum ; If same elements ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimizeleftOverSum ( int a [ ] , int n ) { vector < int > v1 , v2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 ) v1 . push_back ( a [ i ] ) ; else v2 . push_back ( a [ i ] ) ; } if ( v1 . size ( ) > v2 . size ( ) ) { sort ( v1 . begin ( ) , v1 . end ( ) ) ; sort ( v2 . begin ( ) , v2 . end ( ) ) ; int x = v1 . size ( ) - v2 . size ( ) - 1 ; int sum = 0 ; int i = 0 ; while ( i < x ) { sum += v1 [ i ++ ] ; } return sum ; } else if ( v2 . size ( ) > v1 . size ( ) ) { sort ( v1 . begin ( ) , v1 . end ( ) ) ; sort ( v2 . begin ( ) , v2 . end ( ) ) ; int x = v2 . size ( ) - v1 . size ( ) - 1 ; int sum = 0 ; int i = 0 ; while ( i < x ) { sum += v2 [ i ++ ] ; } return sum ; } else return 0 ; } int main ( ) { int a [ ] = { 2 , 2 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MinimizeleftOverSum ( a , n ) ; return 0 ; }