📜  来自所有长度为 K 的子数组的最大 MEX

📅  最后修改于: 2021-09-08 11:35:13             🧑  作者: Mango

给定一个由N 个不同整数和一个整数K组成的数组arr[] ,任务是从所有长度为K 的子数组中找到最大的MEX

例子:

朴素的方法:最简单的方法是生成所有长度为K 的子数组,并找到每个子数组的 MEX 。找到所有MEX 后,打印获得的最大值。

时间复杂度: O(K * N 2 )
辅助空间: O(1)

Efficient Approach:优化上述方式,思路是使用数据结构Set and Sliding Window Technique。请按照以下步骤解决问题:

  • 初始化一个集合S来存储当前子数组中不存在的值,并最初在其中插入1N + 1 个数字,因为最初窗口的大小是0
  • 遍历范围[0, K – 1]并从集合中删除arr[i] ,集合的第一个元素是从索引0和长度K开始的子数组的MEX ,初始化变量mex并将该值存储在mex 中
  • 现在从K迭代到N – 1并插入arr[i]以设置和删除arr[i – K]并更新mex = max(mex, first element of set)。
  • 完成上述步骤后,将mex打印为长度为K 的数组中的最大MEX

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to return maximum MEX of
// all K length subarray
void maxMEX(int arr[], int N, int K)
{
    // Stores element from 1 to N + 1
    // is nor present in subarray
    set s;
 
    // Store number 1 to N + 1 in set s
    for (int i = 1; i <= N + 1; i++)
        s.insert(i);
 
    // Find the MEX of K length subarray
    // starting from index 0
    for (int i = 0; i < K; i++)
        s.erase(arr[i]);
 
    int mex = *(s.begin());
 
    // Find the MEX of all subarray of
    // length K by erasing arr[i]
    // and inserting arr[i-K]
    for (int i = K; i < N; i++) {
        s.erase(arr[i]);
 
        s.insert(arr[i - K]);
 
        // Store first element of set
        int firstElem = *(s.begin());
 
        // Updating mex
        mex = max(mex, firstElem);
    }
 
    // Print maximum MEX of all K
    // length subarray
    cout << mex << ' ';
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 3, 2, 1, 4 };
 
    // Given length of subarray
    int K = 2;
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxMEX(arr, N, K);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG {
 
    // Function to return maximum
    // MEX of all K length subarray
    static void maxMEX(int arr[], int N, int k)
    {
        // Stores element from
        // 1 to N + 1 is nor
        // present in subarray
       
        // We need a Tree Set since
        // we want to store the
        // elements in ascending
        // order
        TreeSet s = new TreeSet<>();
 
        // Store number 1 to
        // N + 1 in set s
          for(int l=1;l<=N+1;l++)   
          s.add(l);
          // i and j point to the start of the array
          // i.e index 0
          int i=0;
          int j=0;
           
          int mex = 0;
          // mex variable which stores the mex for
          // generated subArrays
          int maxMex = Integer.MIN_VALUE;
          //maxMex contains the maximum mex value for all subArrays
           
          while(j < N)
        {
          if(s.contains(arr[j]))
             s.remove(arr[j]);
          int windowSize = j-i+1;
          // window size at any instant is given by j-i+1;
          if(windowSize < k)
             j++;
             // here, windowSize < k , i.e we haven't reached the first
             // window of size k yet.. so we increment j;
          else if(windowSize == k)
          {
            //here , windowSize equals k, we are to get an answer everytime
            // we reached the windowSize of k , first element of the set has
            // mex for this subArray;
            mex = s.pollFirst();
            // set.pollFirst() function removes the firstElement in the treeset;
            maxMex = Math.max(maxMex,mex);
             
            // before sliding the window , we need to undo the calculations
            // done at the starting point , i.e i;
            s.add(arr[i]);
            i++;
            j++;
            // sliding the window by 1 each in i and j , so as to maintain
            // the windowSize k;
          }
        }
        System.out.println(maxMex);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int arr[] = { 6, 1, 3, 2, 4 };
 
        // Given length of subarray
        int K = 3;
 
        // Size of the array
        int N = arr.length;
 
        // Function Call
        maxMEX(arr, N, K);
    }
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function to return maximum MEX of
# all K length subarray
 
 
def maxMEX(arr, N, K):
 
    # Stores element from 1 to N + 1
    # is nor present in subarray
    s = set()
 
    # Store number 1 to N + 1 in set s
    for i in range(1, N + 2):
        s.add(i)
 
    # Find the MEX of K length subarray
    # starting from index 0
    for i in range(K):
        s.remove(arr[i])
 
    mex = list(s)[0]
 
    # Find the MEX of all subarray of
    # length K by erasing arr[i]
    # and inserting arr[i-K]
    for i in range(K, N):
        s.remove(arr[i])
 
        s.add(arr[i - K])
 
        # Store first element of set
        firstElem = list(s)[0]
 
        # Updating mex
        mex = max(mex, firstElem)
 
    # Print maximum MEX of all K
    # length subarray
    print(mex)
 
 
# Driver code
if __name__ == '__main__':
 
    # Given array
    arr = [3, 2, 1, 4]
 
    # Size of the array
    N = len(arr)
 
    # Given length of subarray
    K = 2
 
    # Function Call
    maxMEX(arr, N, K)
 
# This code is contributed by Shivam Singh


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG {
 
    // Function to return maximum
    // MEX of all K length subarray
    static void maxMEX(int[] arr, int N, int K)
    {
        // Stores element from
        // 1 to N + 1 is nor
        // present in subarray
        HashSet s = new HashSet();
 
        // Store number 1 to
        // N + 1 in set s
        for (int i = 1; i <= N + 1; i++)
            s.Add(i);
 
        // Find the MEX of K length
        // subarray starting from index 0
        for (int i = 0; i < K; i++)
            s.Remove(arr[i]);
 
        List v = new List();
        foreach(int i in s) { v.Add(i); }
        int mex = v[0];
 
        // Find the MEX of all subarray of
        // length K by erasing arr[i]
        // and inserting arr[i-K]
        for (int i = K; i < N; i++)
        {
            v.Remove(arr[i]);
            v.Add(arr[i - K]);
 
            // Store first element
            // of set
            int firstElem = v[0];
 
            // Updating mex
            mex = Math.Max(mex, firstElem);
        }
 
        // Print maximum MEX of all K
        // length subarray
        Console.Write(mex - 2 + " ");
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        // Given array
        int[] arr = { 3, 2, 1, 4 };
 
        // Given length of subarray
        int K = 2;
 
        // Size of the array
        int N = arr.Length;
 
        // Function Call
        maxMEX(arr, N, K);
    }
}
 
// This code is contributed by gauravrajput1


Javascript


输出
3 

时间复杂度: O(N * log N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live