Minimize 0 by optimally replacing non zero elements with -1
Last Updated :
13 Mar, 2023
Given an integer N, denoting the size of a circular array containing non-zero elements and an array arr[] of size M having the indices of zeroes in the circular array. In each moment, elements adjacent to 0 (except -1) change to 0. The task is to find the minimum number of 0s that will be present in the circular array if we optimally replace one non-zero element with -1 in each moment.
Examples:
Input: N = 10, M = 3, arr[] = {2, 5, 7}
Output: 7
Explanation:
During first iteration, indices 2, 5, and 7 have value 0. Choose index 1 and make curr[1] = -1.
During second iteration, indices 2, 3, 4, 5, 6, 7, and 8 have 0. Choose index 9 to make curr[9] = -1.
During third iteration, no more elements can be made zero. So finally number of 0's is 7.
Input: N = 6, M = 2, arr[] = {2, 5}
Output: 5
Approach: This can be solved using the following idea:
The key observation is that we need place -1 s in non-zero segments. The optimal idea is to prioritize the longer segments because the loss of non-zero elements will last longer than shorter segments and will change more number of non-zero elements to 0.
- If there are x elements in a segment and the process last y moments, then there will be x-2*y elements at the end which are not 0. Simultaneously, every moment we can make at least one element -1, which indicates that if x−2*y>0, we have an opportunity to get one element -1.
Follow the below steps to implement the idea:
- First sort the array arr[].
- Make an array to store the difference between consecutive elements.
- Sort the newly generated array in decreasing order.
- Initialize a variable res to store the number of non-zero elements
- Traverse the new array and count the new non-zero elements and
- If the number of elements between two consecutive elements of arrays is 1 then make res = res+1.
- Otherwise, make res = res+x-1.
- Return N - res.
Below is the implementation for the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum number of zeroes
// in curr[] array
void findStability(int n, int m, vector<int>& arr)
{
// Sort the array
sort(arr.begin(), arr.end());
arr.push_back(arr[0]);
vector<int> dist;
for (int i = 1; i <= m; i++) {
int curr = arr[i] - arr[i - 1] - 1;
if (curr < 0) {
curr += n;
}
// Push the distance present between
// index of arr[]
dist.push_back(curr);
}
sort(dist.begin(), dist.end(), greater<int>());
int res = 0, curr = 0;
for (int i : dist) {
int x = i;
x -= curr;
if (x == 1) {
res++;
curr++;
}
else if (x > 1) {
res += x - 1;
curr += 4;
}
}
// Return minimum number of zeroes
cout << n - res << '\n';
}
// Driver Code
int main()
{
int N = 10, M = 3;
vector<int> arr = { 3, 6, 8 };
// Function call
findStability(N, M, arr);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find minimum number of zeroes in curr[]
// array
static void findStability(int n, int m,
List<Integer> arr)
{
// Sort the array
Collections.sort(arr);
arr.add(arr.get(0));
List<Integer> dist = new ArrayList<>();
for (int i = 1; i <= m; i++) {
int curr = arr.get(i) - arr.get(i - 1) - 1;
if (curr < 0) {
curr += n;
}
// Push the distance present between index of
// arr[]
dist.add(curr);
}
Collections.sort(dist, Collections.reverseOrder());
int res = 0, curr = 0;
for (int i : dist) {
int x = i;
x -= curr;
if (x == 1) {
res++;
curr++;
}
else if (x > 1) {
res += x - 1;
curr += 4;
}
}
// Return minimum number of zeroes
System.out.println(n - res);
}
public static void main(String[] args)
{
int N = 10, M = 3;
List<Integer> arr
= new ArrayList<>(Arrays.asList(3, 6, 8));
// Function call
findStability(N, M, arr);
}
}
// This code is contributed by karthik.
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find minimum number of zeroes in curr[]
// array
static void findStability(int n, int m,
List<int> arr)
{
// Sort the array
arr.Sort();
arr.Add(arr[0]);
List<int> dist = new List<int>();
int curr;
for (int i = 1; i <= m; i++) {
curr = arr[i] - arr[i - 1] - 1;
if (curr < 0) {
curr += n;
}
// Push the distance present between index of
// arr[]
dist.Add(curr);
}
dist.Sort((x, y) => y.CompareTo(x));
int res = 0;
curr = 0;
foreach (var i in dist) {
int x = i;
x -= curr;
if (x == 1) {
res++;
curr++;
}
else if (x > 1) {
res += x - 1;
curr += 4;
}
}
// Return minimum number of zeroes
Console.WriteLine(n - res);
}
static public void Main (){
int N = 10, M = 3;
List<int> arr
= new List<int>{3, 6, 8};
// Function call
findStability(N, M, arr);
}
}
JavaScript
// Javascript code to implement the approach
// Function to find minimum number of zeroes
// in curr[] array
function findStability( n, m, arr)
{
// Sort the array
arr.sort();
arr.push(arr[0]);
let dist=new Array();
for (let i = 1; i <= m; i++) {
let curr = arr[i] - arr[i - 1] - 1;
if (curr < 0) {
curr += n;
}
// Push the distance present between
// index of arr[]
dist.push(curr);
}
dist.sort();
dist.reverse();
let res = 0, curr = 0;
for (let i of dist) {
let x = i;
x -= curr;
if (x == 1) {
res++;
curr++;
}
else if (x > 1) {
res += x - 1;
curr += 4;
}
}
// Return minimum number of zeroes
document.write(n - res );
}
// Driver Code
let N = 10, M = 3;
let arr = [ 3, 6, 8 ];
// Function call
findStability(N, M, arr);
Python3
# Python code to implement the approach
import sys
# Function to find minimum number of zeroes
# in curr[] array
def findStability(n, m, arr):
# Sort the array
arr.sort()
arr.append(arr[0])
dist = []
for i in range(1, m+1):
curr = arr[i] - arr[i-1] - 1
if curr < 0:
curr += n
# Push the distance present between
# index of arr[]
dist.append(curr)
dist.sort(reverse=True)
res = 0
curr = 0
for i in dist:
x = i
x -= curr
if x == 1:
res += 1
curr += 1
elif x > 1:
res += x - 1
curr += 4
# Return minimum number of zeroes
print(n - res)
# Driver Code
if __name__ == "__main__":
N = 10
M = 3
arr = [3, 6, 8]
# Function call
findStability(N, M, arr)
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Related Articles:
Similar Reads
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:
5 min read
Minimize the sum of MEX by removing all elements of array Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
7 min read
Minimize operations to convert Array elements to 0s Given an array nums[] of length N containing non-negative integers, the task is to convert all elements from index 0 to N-2 to zero, after doing the below operations minimum number of times. In one operation select two indices i and j such that i < j and all the elements between i and j has to be
6 min read
Minimize subtraction of Array elements to make X at most 0 Given a number X, and an array arr[] of length N containing the N numbers. The task is to find the minimum number of operations required to make X non-positive. In one operation: Select any one number Y from the array and reduce X by Y. Then make Y = Y/2 (take floor value if Y is odd).If it is not p
9 min read
Maximize the cost of reducing array elements Given an array arr[] of N positive integers. We can choose any one index(say K) of the array and reduce all the elements of the array from index 0 to K - 1 by 1. The cost of this operation is K. If at any index(say idx) element is reduced to 0 then we can't perform this operation in the range [idx,
6 min read