Minimize the non-zero elements in the Array by given operation
Given an array arr[] of length N, the task is to minimize the count of the number of non-zero elements by adding the value of the current element to any of its adjacent element and subtracting from the current element at most once.
Examples:
Input: arr[] = { 1, 0, 1, 0, 0, 1 }
Output: 2
Explanation:
Operation 1: arr[0] -> arr[1], arr[] = {0, 1, 1, 0, 0, 1}
Operation 2: arr[2] -> arr[1], arr[] = {0, 2, 0, 0, 0, 1}
Count of non-zero elements = 2
Input: arr[] = { 1, 0, 1, 1, 1, 0, 1 }
Output: 3
Explanation:
Operation 1: arr[2] -> arr[3], arr[] = {1, 0, 0, 2, 1, 0, 1}
Operation 2: arr[4] -> arr[3], arr[] = {1, 0, 0, 3, 0, 0, 1}
Count of non-zero elements = 3
Approach: The idea is to use greedy algorithms to choose greedily at each step. The key observation in the problem is there can be only three possibilities of three consecutive indices i, j and k, i.e.
- Both the end index have non-zero element.
- Any one of the index have non-zero element.
In the above two cases, we can always add the values to the middle element and subtract to the adjacent elements. Similarly, we can greedily choose the operations and update the elements of the array to minimize the non-zero elements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minOccupiedPosition( int A[], int n)
{
int minPos = 0;
for ( int i = 0; i < n; ++i) {
if (A[i] > 0) {
++minPos;
i += 2;
}
}
return minPos;
}
int main()
{
int A[] = { 8, 0, 7, 0, 0, 6 };
int n = sizeof (A) / sizeof (A[0]);
cout << minOccupiedPosition(A, n);
return 0;
}
|
Java
class GFG{
static int minOccupiedPosition( int A[], int n)
{
int minPos = 0 ;
for ( int i = 0 ; i < n; ++i)
{
if (A[i] > 0 ) {
++minPos;
i += 2 ;
}
}
return minPos;
}
public static void main(String[] args)
{
int A[] = { 8 , 0 , 7 , 0 , 0 , 6 };
int n = A.length;
System.out.print(minOccupiedPosition(A, n));
}
}
|
Python3
def minOccupiedPosition(A, n):
minPos = 0
i = 0
while i < n:
if (A[i] > 0 ):
minPos + = 1
i + = 2
i + = 1
return minPos
if __name__ = = '__main__' :
A = [ 8 , 0 , 7 , 0 , 0 , 6 ]
n = len (A)
print (minOccupiedPosition(A, n))
|
C#
using System;
class GFG {
static int minOccupiedPosition( int [] A, int n)
{
int minPos = 0;
for ( int i = 0; i < n; ++i)
{
if (A[i] > 0)
{
++minPos;
i += 2;
}
}
return minPos;
}
static void Main()
{
int [] A = { 8, 0, 7, 0, 0, 6 };
int n = A.Length;
Console.WriteLine(minOccupiedPosition(A, n));
}
}
|
Javascript
<script>
function minOccupiedPosition( A, n)
{
var minPos = 0;
for ( var i = 0; i < n; ++i) {
if (A[i] > 0) {
++minPos;
i += 2;
}
}
return minPos;
}
var A = [ 8, 0, 7, 0, 0, 6 ];
var n = A.length;
document.write(minOccupiedPosition(A, n));
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(1)
Last Updated :
10 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...