int totalFruit ( vector< int > & tree, int K) {
int n = tree. size ( ) ;
int left = 0 ;
int right = 0 ;
vector< int > mp ( n, 0 ) ;
int ans = INT_MIN;
int count = 0 ;
while ( right < n) {
if ( mp[ tree[ right] ] == 0 ) {
count++ ;
}
mp[ tree[ right] ] ++ ;
while ( count > K) {
mp[ tree[ left] ] -- ;
if ( mp[ tree[ left] ] == 0 ) {
count-- ;
}
left++ ;
}
right++ ;
ans = max ( ans, right - left) ;
}
return ans;
}
int numSubarrayBoundedMax ( vector< int > & nums, int left, int right) {
return maxK ( nums, right) - maxK ( nums, left - 1 ) ;
}
int maxK ( vector< int > & nums, int k) {
int left = 0 ;
int right = 0 ;
int ans = 0 ;
int n = nums. size ( ) ;
while ( right < n) {
if ( nums[ right] > k) {
right++ ;
left = right;
continue ;
}
right++ ;
ans + = right - left;
}
return ans;
}
int subarraysWithKDistinct ( vector< int > & nums, int k) {
return maxK ( nums, k) - maxK ( nums, k - 1 ) ;
}
int maxK ( vector< int > & nums, int k)
{
vector< int > mp ( nums. size ( ) + 1 , 0 ) ;
int left = 0 ;
int right = 0 ;
int count = 0 ;
int res = 0 ;
while ( right < nums. size ( ) ) {
if ( mp[ nums[ right] ] == 0 ) {
count++ ;
}
mp[ nums[ right] ] ++ ;
right++ ;
while ( count > k) {
mp[ nums[ left] ] -- ;
if ( mp[ nums[ left] ] == 0 ) {
count-- ;
}
left++ ;
}
res + = right - left;
}
return res;
}