Member-only story
Minimum Steps to Make Product of an Array equal to One | Python & C++ | Coding Interview
This problem belongs to the category of simple maths, and it does not require you to know any fancy algorithms. It's more likely that an aspirant may try to solve it using not-so-simple approaches, which can be solved by simple addition and subtraction. I will explain the problem and its solution in detail in this article.
The code in both the languages (python and c++), along with its explanation, is given below.
Definition
Given a list of n integers, make the minimum number of increments or decrements so that the product of the list becomes 1. We want the minimum number of steps required to change the list.
We have two options for each element; either we can increase or decrease to a value so that the product of the whole array becomes one. We will keep track of total increments and decrements. When I say increment or decrement, it's an increment or decrement of 1.
Let’s some examples to make the problem clear.
Example 1:
Input: A = [3 5 2 -5 0]
Output: 14
Explanation:
Change 3 to 1 using 2 steps of decrements.
Change 5 to 1 using 4 steps of decrements.
Change 2 to…