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
Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →