C++ code to count numbers after division elements greater than half of array size

C++Server Side ProgrammingProgramming

<p>Suppose we have an array A with n elements. We have to find some non-zero integer d, such that such that, after each number in the array is divided by d, the number of positive values that are presented in the array is greater than or equal to the half of the array size. If there are multiple values of d that satisfy the condition. If there are multiple answers, return any one of them.</p><p>So, if the input is like A = [10, 0, -7, 2, 6], then the output will be 4, because here n = 5 , so we need at least $\mathrm{\left \lceil 5/2\right \rceil=3}$ elements after division. If d = 4, the array after division will be [2.5, 0, &minus;1.75, 0.5, 1.5], in which there are 3 positive numbers are 2.5, 0.5 and 1.5.</p><h2>Steps</h2><p>To solve this, we will follow these steps &minus;</p><pre class="just-code notranslate language-cpp" data-lang="cpp">z := 0, f := 0 n := size of A for initialize i := 0, when i &lt; n, update (increase i by 1), do: &nbsp; &nbsp;a := A[i] &nbsp; &nbsp;if a &gt; 0, then: &nbsp; &nbsp; &nbsp; (increase z by 1) &nbsp; &nbsp;if a &lt; 0, then: &nbsp; &nbsp; &nbsp; (increase f by 1) if 2 * z &gt;= n, then: &nbsp; &nbsp; &nbsp; return 1 otherwise when 2 * f &gt;= n, then: &nbsp; &nbsp;return -1 Otherwise &nbsp; &nbsp;return 0</pre><h2>Example</h2><p>Let us see the following implementation to get better understanding &minus;</p><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; int solve(vector&lt;int&gt; A){ &nbsp; &nbsp;int z = 0, f = 0; &nbsp; &nbsp;int n = A.size(); &nbsp; &nbsp;for (int i = 0; i &lt; n; i++){ &nbsp; &nbsp; &nbsp; int a = A[i]; &nbsp; &nbsp; &nbsp; if (a &gt; 0) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;z++; &nbsp; &nbsp; &nbsp; if (a &lt; 0) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;f++; &nbsp; &nbsp;} &nbsp; &nbsp;if (2 * z &gt;= n) &nbsp; &nbsp; &nbsp; return 1; &nbsp; &nbsp;else if (2 * f &gt;= n) &nbsp; &nbsp; &nbsp; return -1; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; return 0; } int main(){ &nbsp; &nbsp;vector&lt;int&gt; A = { 10, 0, -7, 2, 6 }; &nbsp; &nbsp;cout &lt;&lt; solve(A) &lt;&lt; endl; }</pre><h2>Input</h2><pre class="result notranslate">{ 10, 0, -7, 2, 6 }</pre><h2>Output</h2><pre class="result notranslate">1</pre>
raja
Updated on 29-Mar-2022 11:20:32

Advertisements