Minimize cost to convert all array elements to 0 | Function to calculate the minimum cost of converting all array elements to 0 s ; Stores subarrays of 0 s only ; Traverse the array ; If consecutive 0 s occur ; Increment if needed ; Push the current length of consecutive 0 s in a vector ; Update lengths as 0 ; Sorting vector ; Stores the number of subarrays consisting of 1 s ; Traverse the array ; If current element is 1 ; Otherwise ; Increment count of consecutive ones ; Stores the minimum cost ; Traverse the array ; First element ; Traverse the subarray sizes ; Update cost ; Cost of performing X and Y operations ; Find the minimum cost ; Print the minimum cost ; Driver Code ; Function Call
function minimumCost ( binary , n , a , b ) { var groupOfZeros = [ ] ; var len = 0 , i = 0 ; var increment_need = true ; while ( i < n ) { increment_need = true ; while ( i < n && binary [ i ] == 0 ) { len ++ ; i ++ ; increment_need = false ; } if ( increment_need == true ) { i ++ ; } if ( len != 0 ) { groupOfZeros . push ( len ) ; } len = 0 ; } groupOfZeros . sort ( ( a , b ) => a - b ) ; i = 0 ; var found_ones = false ; var NumOfOnes = 0 ; while ( i < n ) { found_ones = false ; while ( i < n && binary [ i ] == 1 ) { i ++ ; found_ones = true ; } if ( found_ones == false ) i ++ ; else NumOfOnes ++ ; } var ans = 1000000000 ; for ( var i = 0 ; i < n ; i ++ ) { var curr = 0 , totalOnes = NumOfOnes ; if ( i == 0 ) { curr = totalOnes * a ; } else { var mark = i , num_of_changes = 0 ; groupOfZeros . forEach ( x => { if ( mark >= x ) { totalOnes -- ; mark -= x ; num_of_changes += x ; } } ) ; curr = ( num_of_changes * b ) + ( totalOnes * a ) ; } ans = Math . min ( ans , curr ) ; } document . write ( ans ) ; } var arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] ; var N = arr . length ; var X = 10 , Y = 4 ; minimumCost ( arr , N , X , Y ) ;