Reduce every element of the array to it’s half retaining the sum zero
Last Updated :
23 Jul, 2022
Given an array arr[] of N integers with total element sum equal to zero. The task is to reduce every element to it’s half such that the total sum remain zero. For every odd element X in the array, it could be reduced to either(X + 1) / 2 or (X – 1) / 2.
Examples:
Input: arr[] = {-7, 14, -7}
Output: -4 7 -3
-4 + 7 -3 = 0
Input: arr[] = {-14, 14}
Output: -7 7
Approach: All the even elements could be divided by 2 but for odd elements, they have to be alternatively reduced to (X + 1) / 2 and (X – 1) / 2 in order to retain the original sum (i.e. 0) in the final array.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void half( int arr[], int n)
{
int i;
int flag = 0;
for (i = 0; i < n; i++)
{
if (arr[i] % 2 == 0 )
cout << arr[i] / 2 << " " ;
else
{
if (flag == 0)
{
cout << arr[i] / 2 - 1 << " " ;
flag = 1;
}
else
{
int q = arr[i] / 2;
cout<<q << " " ;
flag = 0;
}
}
}
}
int main ()
{
int arr[] = {-7, 14, -7};
int len = sizeof (arr)/ sizeof (arr[0]);
half(arr, len) ;
return 0;
}
|
Java
class GFG
{
static void half( int arr[], int n)
{
int i;
int flag = 0 ;
for (i = 0 ; i < n; i++)
{
if (arr[i] % 2 == 0 )
System.out.print(arr[i] / 2 + " " );
else
{
if (flag == 0 )
{
System.out.print(arr[i] / 2 - 1 + " " );
flag = 1 ;
}
else
{
int q = arr[i] / 2 ;
System.out.print(q + " " );
flag = 0 ;
}
}
}
}
public static void main (String[] args)
{
int arr[] = {- 7 , 14 , - 7 };
int len = arr.length;
half(arr, len) ;
}
}
|
Python3
def half(arr, n) :
flag = 0
for i in range (n):
if arr[i] % 2 = = 0 :
print (arr[i] / / 2 , end = " " )
else :
if flag = = 0 :
print (arr[i] / / 2 , end = " " )
flag = 1
else :
q = arr[i] / / 2
q + = 1
print (q, end = " " )
flag = 0
arr = [ - 7 , 14 , - 7 ]
half(arr, len (arr))
|
C#
using System;
class GFG
{
static void half( int []arr, int n)
{
int i;
int flag = 0;
for (i = 0; i < n; i++)
{
if (arr[i] % 2 == 0 )
Console.Write(arr[i] / 2 + " " );
else
{
if (flag == 0)
{
Console.Write(arr[i] / 2 - 1 + " " );
flag = 1;
}
else
{
int q = arr[i] / 2;
Console.Write(q + " " );
flag = 0;
}
}
}
}
public static void Main ()
{
int [] arr = {-7, 14, -7};
int len = arr.Length;
half(arr, len) ;
}
}
|
Javascript
<script>
function half(arr, n)
{
let i;
let flag = 0;
for (i = 0; i < n; i++)
{
if (arr[i] % 2 == 0 )
document.write(arr[i] / 2 + " " );
else
{
if (flag == 0)
{
document.write(Math.ceil(arr[i] / 2) - 1 + " " );
flag = 1;
}
else
{
let q = Math.ceil(arr[i] / 2);
document.write(q + " " );
flag = 0;
}
}
}
}
let arr = [-7, 14, -7];
let len = arr.length;
half(arr, len) ;
</script>
|
Time Complexity : O(n) ,as we are traversing once on the array.
Space Complexity : O(1) ,as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...