Sublists Containing Maximum and Minimum - Google Top Interview Questions
Problem Statement :
You are given a list of integers nums and you can remove at most one element in the list. Return the maximum number of sublists that contain both the maximum and minimum elements of the resulting list. The answer is guaranteed to fit in a 32-bit signed integer. Constraints n ≤ 100,000 where n is the length of nums Example 1 Input nums = [2, 1, 5, 1, 3, 9] Output 8 Explanation If we remove 9 we'd get [2, 1, 5, 1, 3] and there's eight sublists where it contains both the max and the min: [1, 5] [5, 1] [1, 5, 1] [2, 1, 5] [5, 1, 3] [1, 5, 1, 3] [2, 1, 5, 1] [2, 1, 5, 1, 3] Example 2 Input nums = [5, 5] Output 3 Explanation In this case, we don't remove any element. There's three sublists which contain both the max and the min: [5], [5] and [5, 5].
Solution :
Solution in C++ :
using ll = long long;
/*
number of sublists containing both the max as well as the min elements
*/
int numSublists(const vector<int>& nums) {
ll mi = INT_MAX + 1LL, mx = INT_MIN - 1LL;
int sz = nums.size(), res = 0, posMin, posMax;
for (int i = sz - 1; i >= 0; --i) {
if (mi > nums[i] || mx < nums[i]) res = 0;
mi = min(mi, (long long)nums[i]);
mx = max(mx, (long long)nums[i]);
if (nums[i] == mi) posMin = i;
if (nums[i] == mx) posMax = i;
res += sz - max(posMax, posMin);
}
return res;
}
int solve(vector<int>& nums) {
if (nums.empty()) return 0;
vector<int> minRemoved = nums;
minRemoved.erase(min_element(minRemoved.begin(), minRemoved.end()));
vector<int> maxRemoved = nums;
maxRemoved.erase(max_element(maxRemoved.begin(), maxRemoved.end()));
return max({numSublists(nums), numSublists(minRemoved), numSublists(maxRemoved)});
}
Solution in Java :
import java.util.*;
class Solution {
public int solve(int[] nums) {
int N = nums.length;
if (N == 0)
return 0;
if (N == 1)
return 1;
// find the max and the min element
int min = nums[0];
int minI = 0;
int cntMin = 1;
int max = nums[0];
int maxI = 0;
int cntMax = 1;
for (int i = 1; i < N; i++) {
if (nums[i] < min) {
min = nums[i];
minI = i;
cntMin = 1;
} else if (nums[i] == min) {
cntMin++;
}
if (nums[i] > max) {
max = nums[i];
maxI = i;
cntMax = 1;
} else if (nums[i] == max) {
cntMax++;
}
}
int ans = helper(nums); // don't remove anything
if (cntMin == 1)
ans = Math.max(ans, helper(newArr(nums, minI)));
if (cntMax == 1)
ans = Math.max(ans, helper(newArr(nums, maxI)));
return ans;
}
public int[] newArr(int[] nums, int index) {
int N = nums.length;
int[] newNums = new int[N - 1];
for (int i = 0; i < index; i++) newNums[i] = nums[i];
for (int i = index + 1; i < N; i++) newNums[i - 1] = nums[i];
return newNums;
}
public int helper(int[] nums) {
int N = nums.length;
int min = nums[0];
int max = nums[0];
for (int n : nums) {
min = Math.min(min, n);
max = Math.max(max, n);
}
if (min == max) {
// every number is the same
return (N * (N + 1) / 2);
}
// store the indices where the max and min element appear in
TreeSet<Integer> mins = new TreeSet<Integer>();
TreeSet<Integer> maxs = new TreeSet<Integer>();
for (int i = 0; i < N; i++) {
if (nums[i] == min)
mins.add(i);
if (nums[i] == max)
maxs.add(i);
}
int ans = 0;
// find the number of sublists beginning at i that include the max and min.
for (int i = 0; i < N; i++) {
if (mins.isEmpty() || maxs.isEmpty())
break;
int minF = mins.first();
int maxF = maxs.first();
Integer a1 = maxs.ceiling(minF);
Integer a2 = mins.ceiling(maxF);
int ind = Integer.MAX_VALUE;
if (a1 != null)
ind = Math.min(ind, a1);
if (a2 != null)
ind = Math.min(ind, a2);
if (ind == Integer.MAX_VALUE)
break;
ans += (N - ind);
if (minF == i)
mins.remove(i);
if (maxF == i)
maxs.remove(i);
}
return ans;
}
}
Solution in Python :
class Solution:
def solve(self, nums):
if len(nums) <= 1:
return len(nums)
def num_sublists(lst):
res = 0
max_val, min_val = max(lst), min(lst)
min_idx, max_idx = None, None
for i, val in enumerate(lst):
if val == max_val:
max_idx = i
if val == min_val:
min_idx = i
if min_idx is None or max_idx is None:
continue
res += min(min_idx, max_idx) + 1
return res
res = num_sublists(nums)
n = len(nums)
if nums.count(min(nums)) == 1:
idx = nums.index(min(nums))
res = max(res, num_sublists(nums[:idx] + nums[idx + 1 :]))
if nums.count(max(nums)) == 1:
idx = nums.index(max(nums))
res = max(res, num_sublists(nums[:idx] + nums[idx + 1 :]))
return res
View More Similar Problems
Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →