Minimum steps to make the product of the array equal to 1 - GeeksforGeeks

28 Mar, 2022
Given an array arr[] containing N integers. In one step, any element of the array can either be increased or decreased by one. The task is to find minimum steps required such that the product of the array elements becomes 1.
Examples: 
Input: arr[] = { -2, 4, 0 } Output: 5 We can change -2 to -1, 0 to -1 and 4 to 1. So, a total of 5 steps are required to update the elements such that the product of the final array is 1.
Input: arr[] = { -1, 1, -1 } Output: 0  
Approach: Follow the steps below to solve the problem:
The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even.Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1.Similarly, all the negative numbers can be updated to -1.If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even).If the count of -ve numbers are even then they are always going to yield -1.But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
The product of the array elements can only be equal to 1 when there are only 1s and -1s in the array and the count of -1s is even.
Now, all the positive numbers can be reduced to 1 because they are closer to 1 than they are closer to -1.
Similarly, all the negative numbers can be updated to -1.
If there are 0s present in the array then they can be reduced to either 1 or -1 according to the situation (the count of -1s must be even).
If the count of -ve numbers are even then they are always going to yield -1.
But if there are odd number of -ve numbers then they are going to yield an odd number of -1s. To fix that, there are two possibilities: First try to find the count 0s in the array because it will take 1 operation to be -1.If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
First try to find the count 0s in the array because it will take 1 operation to be -1.
If there are no zeros in the array then just add 2 in the answer because it will take two steps to make -1 to 1.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// steps requiredint MinStep(int a[], int n){     // To store the count of 0s, positive    // and negative numbers    int positive = 0,        negative = 0,        zero = 0;     // To store the ans    int step = 0;     for (int i = 0; i < n; i++) {         // If array element is        // equal to 0        if (a[i] == 0) {            zero++;        }         // If array element is        // a negative number        else if (a[i] < 0) {            negative++;             // Extra cost needed            // to make it -1            step = step + (-1 - a[i]);        }         // If array element is        // a positive number        else {            positive++;             // Extra cost needed            // to make it 1            step = step + (a[i] - 1);        }    }     // Now the array will    // have -1, 0 and 1 only    if (negative % 2 == 0) {         // As count of negative is even        // so we will change all 0 to 1        // total cost here will be        // count of 0s        step = step + zero;    }    else {         // If there are zeroes present        // in the array        if (zero > 0) {             // Change one zero to -1            // and rest of them to 1            // Total cost here will            // be count of '0'            step = step + zero;        }         // If there are no zeros in the array        else {             // As no 0s are available so we            // have to change one -1 to 1            // which will cost 2 to            // change -1 to 1            step = step + 2;        }    }     return step;} // Driver codeint main(){    int a[] = { 0, -2, -1, -3, 4 };    int n = sizeof(a) / sizeof(a[0]);     cout << MinStep(a, n);     return 0;}
// Java implementation of the approachclass GFG {     // Function to return the minimum    // steps required    static int MinStep(int a[], int n)    {         // To store the count of 0s, positive        // and negative numbers        int positive = 0,            negative = 0,            zero = 0;         // To store the ans        int step = 0;         for (int i = 0; i < n; i++) {             // If array element is            // equal to 0            if (a[i] == 0) {                zero++;            }             // If array element is            // a negative number            else if (a[i] < 0) {                negative++;                 // Extra cost needed                // to make it -1                step = step + (-1 - a[i]);            }             // If array element is            // a positive number            else {                positive++;                 // Extra cost needed                // to make it 1                step = step + (a[i] - 1);            }        }         // Now the array will        // have -1, 0 and 1 only        if (negative % 2 == 0) {             // As count of negative is even            // so we will change all 0 to 1            // total cost here will be            // count of 0s            step = step + zero;        }        else {             // If there are zeroes present            // in the array            if (zero > 0) {                 // Change one zero to -1                // and rest of them to 1                // Total cost here will                // be count of '0'                step = step + zero;            }             // If there are no zeros in the array            else {                 // As no 0s are available so we                // have to change one -1 to 1                // which will cost 2 to                // change -1 to 1                step = step + 2;            }        }         return step;    }     // Driver code    public static void main(String[] args)    {        int a[] = { 0, -2, -1, -3, 4 };        int n = a.length;         System.out.println(MinStep(a, n));    }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the minimum# steps requireddef MinStep(a, n):         # To store the count of 0s, positive    # and negative numbers    positive = 0;    negative = 0;    zero = 0;     # To store the ans    step = 0;     for i in range(n):                 # If array element is        # equal to 0        if (a[i] == 0):            zero += 1;                     # If array element is        # a negative number        elif (a[i] < 0):             negative += 1;             # Extra cost needed            # to make it -1            step = step + (-1 - a[i]);         # If array element is        # a positive number        else:            positive += 1;             # Extra cost needed            # to make it 1            step = step + (a[i] - 1);     # Now the array will    # have -1, 0 and 1 only    if (negative % 2 == 0):         # As count of negative is even        # so we will change all 0 to 1        # total cost here will be        # count of 0s        step = step + zero;     else:         # If there are zeroes present        # in the array        if (zero > 0):             # Change one zero to -1            # and rest of them to 1            # Total cost here will            # be count of '0'            step = step + zero;         # If there are no zeros in the array        else:             # As no 0s are available so we            # have to change one -1 to 1            # which will cost 2 to            # change -1 to 1            step = step + 2;    return step; # Driver codeif __name__ == '__main__':    a = [0, -2, -1, -3, 4];    n = len(a);     print(MinStep(a, n)); # This code is contributed by PrinciRaj1992
// C# implementation of the approachusing System; class GFG {     // Function to return the minimum    // steps required    static int MinStep(int[] a, int n)    {         // To store the count of 0s,        // positive and negative numbers        int positive = 0,            negative = 0,            zero = 0;         // To store the ans        int step = 0;         for (int i = 0; i < n; i++) {             // If array element is            // equal to 0            if (a[i] == 0) {                zero++;            }             // If array element is            // a negative number            else if (a[i] < 0) {                negative++;                 // Extra cost needed                // to make it -1                step = step + (-1 - a[i]);            }             // If array element is            // a positive number            else {                positive++;                 // Extra cost needed                // to make it 1                step = step + (a[i] - 1);            }        }         // Now the array will        // have -1, 0 and 1 only        if (negative % 2 == 0) {             // As count of negative is even            // so we will change all 0 to 1            // total cost here will be            // count of 0s            step = step + zero;        }        else {             // If there are zeroes present            // in the array            if (zero > 0) {                 // Change one zero to -1                // and rest of them to 1                // Total cost here will                // be count of '0'                step = step + zero;            }             // If there are no zeros in the array            else {                 // As no 0s are available so we                // have to change one -1 to 1                // which will cost 2 to                // change -1 to 1                step = step + 2;            }        }         return step;    }     // Driver code    static public void Main()    {        int[] a = { 0, -2, -1, -3, 4 };        int n = a.Length;         Console.Write(MinStep(a, n));    }} // This code is contributed by ajit.
<script> // Javascript implementation of the approach // Function to return the minimum// steps requiredfunction MinStep(a, n){     // To store the count of 0s, positive    // and negative numbers    let positive = 0,        negative = 0,        zero = 0;     // To store the ans    let step = 0;     for (let i = 0; i < n; i++) {         // If array element is        // equal to 0        if (a[i] == 0) {            zero++;        }         // If array element is        // a negative number        else if (a[i] < 0) {            negative++;             // Extra cost needed            // to make it -1            step = step + (-1 - a[i]);        }         // If array element is        // a positive number        else {            positive++;             // Extra cost needed            // to make it 1            step = step + (a[i] - 1);        }    }     // Now the array will    // have -1, 0 and 1 only    if (negative % 2 == 0) {         // As count of negative is even        // so we will change all 0 to 1        // total cost here will be        // count of 0s        step = step + zero;    }    else {         // If there are zeroes present        // in the array        if (zero > 0) {             // Change one zero to -1            // and rest of them to 1            // Total cost here will            // be count of '0'            step = step + zero;        }         // If there are no zeros in the array        else {             // As no 0s are available so we            // have to change one -1 to 1            // which will cost 2 to            // change -1 to 1            step = step + 2;        }    }     return step;} // Driver code    let a = [ 0, -2, -1, -3, 4 ];    let n = a.length;     document.write(MinStep(a, n)); </script>
7
 
Time Complexity: O(N) 
Auxiliary Space: O(1)
YouTubeGeeksforGeeks Practice24.9K subscribersMinimum steps to make product equal to one | Recently asked questions in Amazon interviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 30:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mPPNFyBNyJY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLM68oyaqFM7Q-sv3gA5xbzfgVkoQ0xDrW 
ankthon
jit_t
princiraj1992
subhammahato348
sagarshaw2001
gabaa406
simmytarika5
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7