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 :



title-img




                        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

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →