Minimum operations to make product of adjacent element pair of prefix sum negative | C ++ code for the above approach ; Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( vector < int > a ) { int res = INT_MAX ; int N = a . size ( ) ; for ( int r = 0 ; r < 2 ; r ++ ) { int sum = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( ( i + r ) % 2 ) { if ( sum <= 0 ) { ans += - sum + 1 ; sum = 1 ; } } else { if ( sum >= 0 ) { ans += sum + 1 ; sum = -1 ; } } } res = min ( res , ans ) ; } cout << res ; } int main ( ) { vector < int > a { 1 , -3 , 1 , 0 } ; minOperations ( a ) ; return 0 ; }