Related Articles

# Minimum operations to make product of adjacent element pair of prefix sum negative

• Last Updated : 02 Jul, 2021

Given an array arr[ ] of size N, consider an array prefix[ ] where prefix[i] is the sum of the first i elements of arr. The task is to find the minimum number of operations required to modify the given array such that the product of any two adjacent elements in the prefix array is negative. In one operation you can increment or decrement the value of any element by 1.

Input: arr[] = {1, -3, 1, 0}
Output: 4
Explanation: The sequence can be transformed into 1, -2, 2, -2 by 4 operations, the sum of the prefixes are 1, -1, 1, -1 which satisfy all the conditions.

Input: arr[] = {-1 4 3 2 -5 4}
Output: 8

Approach: The idea is to try out two independent possibilities that either even length prefix sums are positive and odd length prefix sums are negative or vice versa. Follow the steps below to solve the problem:

• Initialize a variable res = INT_MAX to store the minimum number of operations.
• Traverse over the range [0, 1] using the variable r.
• Initialize variables ans = 0  and sum = 0 to store the count of total operations and the current prefix sum respectively.
• Traverse over the range [0, N-1] using the variable i,
• Add arr[i] to the value of sum.
• If the value of (i+r) is odd and if sum is not positive then add sum+1 to ans and update the value of sum to 1.
• Otherwise if (i+r) is even and if sum is not negative then add sum+1 to ans update the value of sum to -1.
• Update the value of res as min(res, ans).
• After completing the above steps print the value of res.

## C++

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

## Java

 `// Java code for the above approach``import` `java.util.*;` `class` `GFG{`` ` `// Function to find minimum operations``// needed to make the product of any``// two adjacent elements in prefix``// sum array negative``static` `void` `minOperations(ArrayList a)``{``    ` `    ``// Stores the minimum operations``    ``int` `res = Integer.MAX_VALUE;``    ``int` `N = a.size();` `    ``for``(``int` `r = ``0``; r < ``2``; r++)``    ``{``        ` `        ``// Stores the prefix sum``        ``// and number of operations``        ``int` `sum = ``0``, ans = ``0``;` `        ``// Traverse the array``        ``for``(``int` `i = ``0``; i < N; i++)``        ``{``            ` `            ``// Update the value of sum``            ``sum += a.get(i);``            ` `            ``// Check if i+r is odd``            ``if` `((i + r) % ``2` `== ``1``)``            ``{``                ` `                ``// Check if prefix sum``                ``// is not positive``                ``if` `(sum <= ``0``)``                ``{``                    ` `                    ``// Update the value of``                    ``// ans and sum``                    ``ans += -sum + ``1``;``                    ``sum = ``1``;``                ``}``            ``}``            ``else``            ``{``                ` `                ``// Check if prefix sum is``                ``// not negative``                ``if` `(sum >= ``0``)``                ``{``                    ` `                    ``// Update the value of``                    ``// ans and sum``                    ``ans += sum + ``1``;``                    ``sum = -``1``;``                ``}``            ``}``        ``}` `        ``// Update the value of res``        ``res = Math.min(res, ans);``    ``}` `    ``// Print the value of res``    ``System.out.print(res);``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``ArrayList a = ``new` `ArrayList();``    ``a.add(``1``);``    ``a.add(-``3``);``    ``a.add(``1``);``    ``a.add(``0``);` `    ``minOperations(a);``}``}``    ` `// This code is contributed by SURENDRA_GANGWAR`

## Python3

 `# python 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``def` `minOperations(a):``  ` `    ``#Stores the minimum operations``    ``res ``=` `100000000000``    ``N ``=` `len``(a)``    ``for` `r ``in` `range``(``0``,``2``):``      ` `        ``# Stores the prefix sum``        ``# and number of operations``        ``sum` `=` `0``        ``ans ``=` `0``        ` `        ``# Traverse the array``        ``for` `i ``in` `range` `(``0``,N):``          ` `            ``# Update the value of sum``            ``sum` `+``=` `a[i]``            ` `            ``# Check if i+r is odd``            ``if` `((i ``+` `r) ``%` `2``):` `                ``# Check if prefix sum``                ``# is not positive``                ``if` `(``sum` `<``=` `0``):``                  ` `                    ``# Update the value of``                    ``# ans and sum``                    ``ans ``+``=` `-``sum` `+` `1``                    ``sum` `=` `1``            ``else``:` `                 ``# Check if prefix sum is``                ``# not negative``                ``if` `(``sum` `>``=` `0``):``                  ` `                    ``# Update the value of``                    ``# ans and sum``                    ``ans ``+``=` `sum` `+` `1``;``                    ``sum` `=` `-``1``;` `        ``# Update the value of res``        ``res ``=` `min``(res, ans)``        ` `    ``# // Print the value of res``    ``print``(res)` `    ``# Driver code``a ``=` `[``1``, ``-``3``, ``1``, ``0``]``minOperations(a);` `# This code is contributed by Stream_Cipher`

## C#

 `// C# code for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{``  ` `// Function to find minimum operations``// needed to make the product of any``// two adjacent elements in prefix``// sum array negative``static` `void` `minOperations(List<``int``> a)``{``  ` `    ``// Stores the minimum operations``    ``int` `res = Int32.MaxValue;``    ``int` `N = a.Count;` `    ``for` `(``int` `r = 0; r < 2; r++)``    ``{``      ` `        ``// Stores the prefix sum``        ``// and number of operations``        ``int` `sum = 0, ans = 0;` `        ``// Traverse the array``        ``for` `(``int` `i = 0; i < N; i++)``        ``{``          ` `            ``// Update the value of sum``            ``sum += a[i];``          ` `            ``// Check if i+r is odd``            ``if` `((i + r) % 2 == 1) {` `                ``// Check if prefix sum``                ``// is not positive``                ``if` `(sum <= 0) {` `                    ``// Update the value of``                    ``// ans and sum``                    ``ans += -sum + 1;``                    ``sum = 1;``                ``}``            ``}``            ``else` `{` `                ``// Check if prefix sum is``                ``// not negative``                ``if` `(sum >= 0) {``                    ``// Update the value of``                    ``// ans and sum``                    ``ans += sum + 1;``                    ``sum = -1;``                ``}``            ``}``        ``}` `        ``// Update the value of res``        ``res = Math.Min(res, ans);``    ``}` `    ``// Print the value of res``    ``Console.Write(res);``}` `// Driver Code``public` `static` `void` `Main()``{``    ``List<``int``> a = ``new` `List<``int``>(){ 1, -3, 1, 0 };` `    ``minOperations(a);``}``}` `// This code is contributed by bgangwar59.`

## Javascript

 ``
Output

`4`

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up