Remove elements to make array satisfy arr[ i+1] < arr[i] for each valid i - GeeksforGeeks

29 May, 2019
Given an array arr[] of non-negative integers. We have to delete elements from this array such that arr[i + 1] > arr[j] for each valid i and this will be counted as one step. We have to apply the same operations until the array has become strictly decreasing. Now the task is to count the number of steps required to get the desired array.
Examples:
Input: arr[] = {6, 5, 8, 4, 7, 10, 9}Output: 2Initially 8, 7 and 10 do not satisfy the conditionso they all are deleted in the first stepand the array becomes {6, 5, 4, 9}In the next step 9 gets deleted andthe array becomes {6, 5, 4} which is strictly decreasing.
Input: arr[] = {1, 2, 3, 4, 5}Output: 1
Approach: The idea is to keep the indices of only required elements that are to be checked against a particular element. Thus, we use a vector to store only the required indices. We insert every index at the back and then remove the indices from back if the following condition is satisfied.
arr[vect.back()] ≥ val[i]
We take another array in which we update the no of steps particular element takes to delete.If status[i] = -1 then element is not to be deleted, 0 denotes first step and so on.... That’s why we will add 1 to the answer.While popping the indices, we repeatedly update the status of elements. If all indices are popped i.e. vect.size() = 0 then this element is not to be deleted so change its status to -1.
Below is the implementation of the above approach:
CPP
Java
Python3
C#
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;int status[100000];  // Function to return the required// number of stepsint countSteps(int* val, int n){    int sol = 0;    vector<int> vec(1, 0);    status[0] = -1;      // Compute the number of steps    for (int i = 1; i < n; ++i) {          // Current status is to        // delete in first step        status[i] = 0;          // Pop the indices while        // condition is satisfied        while (vec.size() > 0               && val[vec.back()] >= val[i]) {              // Inserting the correct            // step no to delete            status[i] = max(status[i],                            status[vec.back()] + 1);            vec.pop_back();        }        if (vec.size() == 0) {              // Status changed to not delete            status[i] = -1;        }          // Pushing a new index in the vector        vec.push_back(i);          // Build the solution from        // smaller to larger size        sol = max(sol, status[i] + 1);    }    return sol;}  // Driver codeint main(){    int val[] = { 6, 5, 8, 4, 7, 10, 9 };    int n = sizeof(val) / sizeof(val[0]);      cout << countSteps(val, n);      return 0;}
// A Java implementation of the approachimport java.util.*;  class GFG {      static int []status = new int[100000];  // Function to return the required// number of stepsstatic int countSteps(int[]val, int n){    int sol = 0;    Vector<Integer> vec = new Vector<>(1);    vec.add(0);    status[0] = -1;      // Compute the number of steps    for (int i = 1; i < n; ++i)     {          // Current status is to        // delete in first step        status[i] = 0;          // Pop the indices while        // condition is satisfied        while (vec.size() > 0            && val[vec.lastElement()] >= val[i])        {              // Inserting the correct            // step no to delete            status[i] = Math.max(status[i],                            status[vec.lastElement()] + 1);            vec.remove(vec.lastElement());        }        if (vec.isEmpty())        {              // Status changed to not delete            status[i] = -1;        }          // Pushing a new index in the vector        vec.add(i);          // Build the solution from        // smaller to larger size        sol = Math.max(sol, status[i] + 1);    }    return sol;}  // Driver codepublic static void main(String[] args) {    int val[] = { 6, 5, 8, 4, 7, 10, 9 };    int n = val.length;      System.out.println(countSteps(val, n));}}  /* This code contributed by PrinciRaj1992 */
# Python3 implementation of the approach   status = [0]*100000;   # Function to return the required # number of steps def countSteps(val, n) :          sol = 0;     vec = [1, 0];     status[0] = -1;       # Compute the number of steps     for i in range(n) :          # Current status is to         # delete in first step         status[i] = 0;           # Pop the indices while         # condition is satisfied         while (len(vec) > 0            and val[vec[len(vec)-1]] >= val[i]) :               # Inserting the correct             # step no to delete             status[i] = max(status[i],                             status[len(vec)-1] + 1);             vec.pop();                   if (len(vec) == 0) :              # Status changed to not delete             status[i] = -1;                     # Pushing a new index in the vector         vec.append(i);           # Build the solution from         # smaller to larger size         sol = max(sol, status[i] + 1);           return sol;     # Driver code if __name__ == "__main__" :       val = [ 6, 5, 8, 4, 7, 10, 9 ];     n = len(val);       print(countSteps(val, n));       # This code is contributed by AnkitRai01
// A C# implementation of the approach using System;using System.Collections.Generic;  class GFG {       static int []status = new int[100000];   // Function to return the required // number of steps static int countSteps(int[]val, int n) {     int sol = 0;     List<int> vec = new List<int>(1);     vec.Add(0);     status[0] = -1;       // Compute the number of steps     for (int i = 1; i < n; ++i)     {           // Current status is to         // delete in first step         status[i] = 0;           // Pop the indices while         // condition is satisfied         while (vec.Count > 0            && val[vec[vec.Count-1]] >= val[i])         {               // Inserting the correct             // step no to delete             status[i] = Math.Max(status[i],                             status[vec[vec.Count-1]] + 1);             vec.Remove(vec[vec.Count-1]);         }         if (vec.Count == 0)         {               // Status changed to not delete             status[i] = -1;         }           // Pushing a new index in the vector         vec.Add(i);           // Build the solution from         // smaller to larger size         sol = Math.Max(sol, status[i] + 1);     }     return sol; }   // Driver code public static void Main(String[] args) {     int []val = { 6, 5, 8, 4, 7, 10, 9 };     int n = val.Length;       Console.WriteLine(countSteps(val, n)); } }   // This code contributed by Rajput-Ji
2

princiraj1992
ankthon
Rajput-Ji
Constructive Algorithms
cpp-vector
Algorithms
Arrays
C++ Programs
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation