Minimum score possible for a player by selecting one or two consecutive array elements from given binary array | Stores the minimum score for each states as map < pair < pos , myturn > , ans > ; Function to find the minimum score after choosing element from array ; Return the stored state ; Base Case ; Player A 's turn ; Find the minimum score ; Store the current state ; Return the result ; Player B 's turn ; Find minimum score ; Store the current state ; Return the result ; Function that finds the minimum penality after choosing element from the given binary array ; Starting position of choosing element from array ; 0 denotes player A turn 1 denotes player B turn ; Function Call ; Function to print the answer ; Minimum penalty ; Calculate sum of all arr elements ; Print the minimum score ; Driver Code
let m = new Map ( ) ; function findMinimum ( arr , N , pos , turn ) { let x = [ pos , turn ] ; if ( m . has ( x ) ) { return m [ x ] ; } if ( pos >= N - 1 ) { return 0 ; } if ( turn == 0 ) { let ans = Math . min ( findMinimum ( arr , N , pos + 1 , 1 ) + arr [ pos ] , findMinimum ( arr , N , pos + 2 , 1 ) + arr [ pos ] + arr [ pos + 1 ] ) ; let v = [ pos , turn ] ; m [ v ] = ans ; return ans ; } if ( turn != 0 ) { let ans = Math . min ( findMinimum ( arr , N , pos + 1 , 0 ) , findMinimum ( arr , N , pos + 2 , 0 ) ) ; let v = [ pos , turn ] ; m [ v ] = ans ; return ans ; } return 0 ; } function countPenality ( arr , N ) { let pos = 0 ; let turn = 0 ; return findMinimum ( arr , N , pos , turn ) + 1 ; } function printAnswer ( arr , N ) { let a = countPenality ( arr , N ) ; let sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } document . write ( a ) ; } let arr = [ 1 , 0 , 1 , 1 , 0 , 1 , 1 , 1 ] ; let N = 8 ; printAnswer ( arr , N ) ;