Minimum increments or decrements required to signs of prefix sum array elements alternating | Function to find the minimum number of increments / decrements of array elements by 1 to make signs of prefix sum array elements alternating ; Case 1. neg - pos - neg ; Stores the current sign of the prefix sum of array ; Stores minimum number of operations for Case 1 ; Traverse the array ; Checking both conditions ; Update the current prefix1 to currentPrefixSum ; Case 2. pos - neg - pos ; Stores the prefix sum of array ; Stores minimum number of operations for Case 1 ; Checking both conditions ; Update the current prefix2 to currentPrefixSum ; Driver Code
def minimumOperations ( A , N ) : NEW_LINE INDENT cur_prefix_1 = 0 NEW_LINE parity = - 1 NEW_LINE minOperationsCase1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_prefix_1 += A [ i ] NEW_LINE if ( cur_prefix_1 == 0 or parity * cur_prefix_1 < 0 ) : NEW_LINE INDENT minOperationsCase1 += abs ( parity - cur_prefix_1 ) NEW_LINE cur_prefix_1 = parity NEW_LINE DEDENT parity *= - 1 NEW_LINE DEDENT cur_prefix_2 = 0 NEW_LINE parity = 1 NEW_LINE minOperationsCase2 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_prefix_2 += A [ i ] NEW_LINE if ( cur_prefix_2 == 0 or parity * cur_prefix_2 < 0 ) : NEW_LINE INDENT minOperationsCase2 += abs ( parity - cur_prefix_2 ) NEW_LINE cur_prefix_2 = parity NEW_LINE DEDENT parity *= - 1 NEW_LINE DEDENT return min ( minOperationsCase1 , minOperationsCase2 ) NEW_LINE DEDENT A = [ 1 , - 3 , 1 , 0 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumOperations ( A , N ) ) NEW_LINE