βœ…Longest subarray not having more than K distinct elements(Contest)

Longest subarray not having more than K distinct elements Difficulty Level : Medium

Problem Statement :

Given N elements and a number K, find the longest subarray which has not more than K distinct elements.(It can have less than K).

Examples:

Input : arr[] = {1, 2, 3, 4, 5}
            k = 6 
Output : 1 2 3 4 5 
Explanation: The whole array has only 5 
distinct elements which is less than k, 
so we print the array itself.

Input: arr[] = {6, 5, 1, 2, 3, 2, 1, 4, 5}
           k = 3
Output: 1 2 3 2 1, 
The output is the longest subarray with 3
distinct elements.

link:https://www.geeksforgeeks.org/longest-subarray-not-k-distinct-elements/

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		
		int []arr = new int[n];
		for(int i=0; i<n; i++){
		    arr[i] = sc.nextInt();
		}
		int left = 0;
		int freq[] = new int[100001];
		int uniquecount = 0;
		int ans =0;
		for(int i=0; i<n ; i++){
		    freq[arr[i]]++;
		    if(freq[arr[i]] == 1){
		        uniquecount++;
		    }
		    while(uniquecount>k-1){
		        freq[arr[left]]--;
		        if(freq[arr[left]] == 0){
		            uniquecount--;
		        }
		        left++;
		    }
		    ans= Math.max(ans, i-left+1);
		}
		System.out.println(ans);
	}
}

Last updated