Related Articles

# Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element

• Difficulty Level : Hard
• Last Updated : 15 Sep, 2021

Given an array arr[] of size N. The task is to maximize the count of subarrays that contain both the minimum and maximum elements of the array by deleting at most one element from the array.

Examples:

Input: arr[] = {7, 2, 5, 4, 3, 1}
Output:
Explanation:
Delete 1 from the array then resultant array will be {7, 2, 5, 4, 3}. So the number of subarrays which contain maximum element 7 and minimum element 2 will be 4 {[7, 2], [7, 2, 5], [7, 2, 5, 4], [7, 2, 5, 4, 3]}

Input: arr[] = {9, 9, 8, 9, 8, 9, 9, 8, 9, 8}
Output: 43

Naive Approach: The simplest approach is to delete every element and then count the number of subarrays having the minimum and maximum element of the resultant array.

Time Complexity: O(N3
Auxiliary Space: O(1)

Efficient Approach: This approach is based on the observation that deletion of elements other than the maximum or minimum element never maximizes the overall result. Below are the steps:

1. Initialize the overall result with INT_MIN.
2. Create a function say proc which returns the number of subarrays containing the smallest and the largest element of the array.
3. To calculate the number of subarrays find the starting and ending index of the subarray using two pointers approach:
• Initialize the smallest and the largest element say low and high with the last element of the array.
• Initialize two pointers p1 and p2 with the last index of array which stores the location of low and high.
• Now, iterate over the array and check if the current element is less than low, then update p1.
• If the current element is more than high, then update p2.
• At each step, update the maximum number of subarrays.
4. Now, calculate the number of subarrays in the following three cases:
• Without removing any element

• After removing the largest element
• After removing the smallest element.
5. Take the maximum of all three cases.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;``// Returns the count of subarrays``// which contains both the maximum and``// minimum elements in the given vector``long` `long` `proc(vector<``int``> &v)``    ``{``  ` `        ``long` `long` `int` `n = v.size();``  ` `        ``// Initialize the low and``        ``// high of array``        ``int` `low = v[n - 1], high = v[n - 1];``        ``long` `long` `int` `p1 = n, p2 = n;``        ``long` `long` `ans = 0;``  ` `        ``for` `(``int` `i = n - 1; i >= 0; i--) {``            ``int` `x = v[i];``  ` `            ``// If current element is``            ``// less than least element``            ``if` `(x < low) {``                ``low = x;``                ``ans = 0;``            ``}``  ` `            ``// If current element is``            ``// more than highest element``            ``else` `if` `(x > high) {``                ``high = x;``                ``ans = 0;``            ``}``  ` `            ``// If current element is``            ``// equal to low or high``            ``// then update the pointers``            ``if` `(x == low)``                ``p1 = i;``            ``if` `(x == high)``                ``p2 = i;``  ` `            ``// Update number of subarrays``            ``ans += n - max(p1, p2);``        ``}``  ` `        ``// Return the result``        ``return` `ans;``    ``}`` ` `// Function to find the maximum``    ``// count of subarrays``long` `long` `subarray(vector<``int``>& v)``{``    ``long` `long` `int` `n=v.size();``    ``if``(n<=1)``    ``return` `n;``    ``long` `long` `ans=proc(v);``    ``int` `low=v,pos_low=0,high=v,pos_high=0;``    ``// Iterate the array to find``    ``// the maximum and minimum element``    ``for` `(``int` `i = 1; i < n; i++) {``            ``int` `x = v[i];``            ``if` `(x < low) {``                ``low = x;``                ``pos_low = i;``            ``}``            ``else` `if` `(x > high) {``                ``high = x;``                ``pos_high = i;``            ``}``        ``}``        ``// Vector after removing the``        ``// minimum element``        ``vector<``int``>u;``         ``// Using assignment operator to copy one``         ``//  vector to other``         ``u=v;``         ``u.erase(u.begin()+pos_low);``         ``ans=max(ans,proc(u));``         ``// Vector after removing the``        ``// maximum element``        ``vector<``int``>w;``        ``w=v;``        ``w.erase(w.begin()+pos_high);``        ``return` `max(ans,proc(w));``    ` `}` `// Driver Code``int` `main()``{``  ` `    ``// Given array``    ``vector<``int``>v;``    ``v.push_back(7);``    ``v.push_back(2);``    ``v.push_back(5);``    ``v.push_back(4);``    ``v.push_back(3);``    ``v.push_back(1);``  ` `  ``// Function Call``  ``cout<

## Java

 `// Java implementation of the above approach``import` `java.util.*;``import` `java.lang.*;` `class` `GFG {` `    ``// Function to find the maximum``    ``// count of subarrays``    ``static` `long` `subarray(List v)``    ``{``        ``int` `n = v.size();``        ``if` `(n <= ``1``)``            ``return` `n;` `        ``long` `ans = proc(v);``        ``int` `low = v.get(``0``), pos_low = ``0``;``        ``int` `high = v.get(``0``), pos_high = ``0``;` `        ``// Iterate the array to find``        ``// the maximum and minimum element``        ``for` `(``int` `i = ``1``; i < n; i++) {``            ``int` `x = v.get(i);``            ``if` `(x < low) {``                ``low = x;``                ``pos_low = i;``            ``}``            ``else` `if` `(x > high) {``                ``high = x;``                ``pos_high = i;``            ``}``        ``}` `        ``// List after removing the``        ``// minimum element``        ``List u``            ``= ``new` `ArrayList<>(``                ``Collections.nCopies(n, ``0``));``        ``Collections.copy(u, v);``        ``u.remove(pos_low);``        ``ans = Math.max(ans, proc(u));` `        ``// List after removing the``        ``// maximum element``        ``List w``            ``= ``new` `ArrayList<>(``                ``Collections.nCopies(n, ``0``));``        ``Collections.copy(w, v);``        ``w.remove(pos_high);` `        ``return` `Math.max(ans, proc(w));``    ``}` `    ``// Returns the count of subarrays``    ``// which contains both the maximum and``    ``// minimum elements in the given list``    ``static` `long` `proc(List v)``    ``{` `        ``int` `n = v.size();` `        ``// Initialize the low and``        ``// high of array``        ``int` `low = v.get(n - ``1``), high = v.get(n - ``1``);``        ``int` `p1 = n, p2 = n;``        ``long` `ans = ``0``;` `        ``for` `(``int` `i = n - ``1``; i >= ``0``; i--) {``            ``int` `x = v.get(i);` `            ``// If current element is``            ``// less than least element``            ``if` `(x < low) {``                ``low = x;``                ``ans = ``0``;``            ``}` `            ``// If current element is``            ``// more than highest element``            ``else` `if` `(x > high) {``                ``high = x;``                ``ans = ``0``;``            ``}` `            ``// If current element is``            ``// equal to low or high``            ``// then update the pointers``            ``if` `(x == low)``                ``p1 = i;``            ``if` `(x == high)``                ``p2 = i;` `            ``// Update number of subarrays``            ``ans += n - Math.max(p1, p2);``        ``}` `        ``// Return the result``        ``return` `ans;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Given array``        ``List arr = Arrays.asList(``7``, ``2``, ``5``, ``4``, ``3``, ``1``);` `        ``// Function Call``        ``System.out.println(subarray(arr));``    ``}``}`

## Javascript

 ``
Output
`4`

Time Complexity: O(N)
Auxiliary Space: O(N)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up