Minimum number of steps required to place all 1 s at a single index | Function to print minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith index ; Count number of 1 s present till i - th index ; Initialize count ; Traverse the array in backward direction ; Steps needed to store all 1 s to the right of i at current index ; Count number of 1 s present after i - th index ; Print the number of steps required ; Driver Code
def minsteps ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE left , right , res = [ 0 ] * n , [ 0 ] * n , [ 0 ] * n NEW_LINE count = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + count NEW_LINE count += A [ i ] NEW_LINE DEDENT count = A [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] + count NEW_LINE count += A [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT res [ i ] = left [ i ] + right [ i ] NEW_LINE print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 0 , 1 , 0 ] NEW_LINE minsteps ( A ) NEW_LINE DEDENT