Maximize removal of adjacent array elements based on their absolute value

Given an array arr[] of positive and negative integers, the task is to print the array after the removal of adjacent array elements starting from the last index of the array.
Array elements can be removed based on the following conditions: 
 

  • Two adjacent elements of opposite sign needs to be compared only.
  • Smaller absolute value of the two adjacent elements of the opposite sign will be discarded.
  • Both equal absolute valued adjacent elements of opposite sign both be discarded.
  • If resultant array is empty then print -1.

Examples: 
 

Input: arr[] = { 2, 7, -6, 3, 8, -5 } 
Output: 2 7 3 8 
Explanation: 
After comparing arr[4] and arr[5], arr[5] is discarded because |8| > |-6|. 
After comparing arr[1] and arr[2], arr[2] is discarded because |7| > |-6|.
Input: arr[] = { 2, 7, -9, 3, 8, -5 } 
Output: -9 3 8 
Explanation: 
After comparing arr[4] and arr[5], arr[5] is discarded because |8| > |-5|. 
After comparing arr[1] and arr[2], arr[1] is discarded because |7| < |-9|. 
After comparing arr[0] and arr[2], arr[0] is discarded because |2| < |-9|. 
 

 

Approach: 
To solve the problem mentioned above, follow the steps given below: 
 



  • Traverse the given input array and if the element is positive then insert it in the vector.
  • If the element is negative then find the correct state of this integer by traversing in the final vector in a reverse manner and check whether the last element in the vector is positive or negative.
  • If it is positive, we check which one of them will get discarded by comparing the absolute value of both the integers.
  • If the vector is empty or the last element in it is negative then we push the current element in the final vector.
  • If by comparing the absolute of both the integers we get the same value then the last element from the vector is discarded.

Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to maximize removals
// of adjacent array elements based
// on their absolute value
#include <bits/stdc++.h>
using namespace std;
  
// Function to find remaining
// array elements after removals
void removals(int arr[], int n)
{
    vector<int> v;
  
    for (int i = 0; i < n; i++) {
        // If i-th element is having
        // positive value (moving right)
        if (arr[i] > 0)
            // Push them into
            // the vector
            v.push_back(arr[i]);
  
        else {
            // If the last element of the vector
            // is of opposite sign and is less
            // than the value of current
            // integer then pop that element
            while (!v.empty() && (v.back() > 0)
                   && v.back() < abs(arr[i]))
                v.pop_back();
  
            // Check if vector is empty or the
            // last element has same sign
            if (v.empty() || v.back() < 0)
                v.push_back(arr[i]);
  
            // Check if the value is same
            else if (v.back() == abs(arr[i]))
                v.pop_back();
        }
    }
  
    // If vector is empty
    if (v.size() == 0) {
        cout << -1;
        return;
    }
  
    // Print the final array
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
  
    return;
}
  
// Driver Code
int main()
{
    int arr[] = { 2, 7, -9, 3, 8, -5 };
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    removals(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to maximize removals
// of adjacent array elements based
// on their absolute value
import java.util.*;
class GFG{
  
// Function to find remaining
// array elements after removals
static void removals(int arr[], int n)
{
    Vector<Integer> v = new Vector<Integer>();
  
    for (int i = 0; i < n; i++) 
    {
        // If i-th element is having
        // positive value (moving right)
        if (arr[i] > 0)
          
            // Push them into
            // the vector
            v.add(arr[i]);
  
        else 
        {
              
            // If the last element of the vector
            // is of opposite sign and is less
            // than the value of current
            // integer then pop that element
            while (!v.isEmpty() && (v.lastElement() > 0) && 
                    v.lastElement() < Math.abs(arr[i]))
                v.remove(v.size()-1);
  
            // Check if vector is empty or the
            // last element has same sign
            if (v.isEmpty() || v.lastElement() < 0)
                v.add(arr[i]);
  
            // Check if the value is same
            else if (v.lastElement() == Math.abs(arr[i]))
                v.remove(v.size() - 1);
        }
    }
  
    // If vector is empty
    if (v.size() == 0)
    {
        System.out.print(-1);
        return;
    }
  
    // Print the final array
    for (int i = 0; i < v.size(); i++) 
    {
        System.out.print(v.get(i) + " ");
    }
    return;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 7, -9, 3, 8, -5 };
  
    int n = arr.length;
  
    removals(arr, n);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to maximize removals
# of adjacent array elements based
# on their absolute value
  
# Function to find remaining
# array elements after removals
def removals(arr, n):
  
    v = []
  
    for i in range(n):
          
        # If i-th element is having
        # positive value (moving right)
        if (arr[i] > 0):
              
            # Push them into
            # the vector
            v.append(arr[i])
  
        else:
              
            # If the last element of the vector
            # is of opposite sign and is less
            # than the value of current
            # integer then pop that element
            while (len(v) != 0 and v[-1] > 0 and 
                                   v[-1] < abs(arr[i])):
                v.pop()
  
            # Check if vector is empty or the
            # last element has same sign
            if (len(v) == 0 or v[-1] < 0):
                v.append(arr[i])
  
            # Check if the value is same
            elif (v[-1] == abs(arr[i])):
                v.pop()
  
    # If vector is empty
    if (len(v) == 0):
        print(-1)
        return
  
    # Print the final array
    for i in range(len(v)):
        print(v[i], end = " ")
  
    return
  
# Driver Code
if __name__ == "__main__":
      
    arr = [ 2, 7, -9, 3, 8, -5 ]
    n = len(arr)
      
    removals(arr, n)
  
# This code is contributed by chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to maximize removals 
// of adjacent array elements based 
// on their absolute value 
using System;
using System.Collections.Generic;
  
class GFG{ 
  
// Function to find remaining 
// array elements after removals 
static void removals(int []arr, int n) 
    List<int> v = new List<int>(); 
  
    for(int i = 0; i < n; i++) 
    
  
        // If i-th element is having 
        // positive value (moving right) 
        if (arr[i] > 0) 
          
            // Push them into 
            // the vector 
            v.Add(arr[i]); 
  
        else
        
              
            // If the last element of the vector 
            // is of opposite sign and is less 
            // than the value of current 
            // integer then pop that element 
            while (v.Count != 0 && (v[v.Count - 1] > 0) && 
                 v[v.Count - 1] < Math.Abs(arr[i])) 
                v.RemoveAt(v.Count - 1); 
  
            // Check if vector is empty or the 
            // last element has same sign 
            if (v.Count == 0 || v[v.Count - 1] < 0) 
                v.Add(arr[i]); 
  
            // Check if the value is same 
            else if (v[v.Count - 1] == Math.Abs(arr[i])) 
                v.RemoveAt(v.Count - 1); 
        
    
  
    // If vector is empty 
    if (v.Count == 0) 
    
        Console.Write(-1); 
        return
    
  
    // Print the readonly array 
    for(int i = 0; i < v.Count; i++) 
    
        Console.Write(v[i] + " "); 
    
    return
  
// Driver Code 
public static void Main(String[] args) 
    int []arr = { 2, 7, -9, 3, 8, -5 }; 
  
    int n = arr.Length; 
  
    removals(arr, n); 
  
// This code is contributed by 29AjayKumar

chevron_right


Output: 

-9 3 8

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : chitranayal, 29AjayKumar