Saturday, 4 Dec 2021
Category: sliding-window

#include using namespace std;  int maxLength(string str, int n,              char c, int k){        int ans = -1;          int cnt = 0;          int left = 0;      for (int right = 0; right < n; right++) {          if (str[right] == c) {            cnt++;        }                  while (cnt > k) {            if (str[left] == c) {                cnt–;            }                                      left++;        }                          ans = max(ans, right – left + 1);    }      return ans;}  int maxConsecutiveSegment(string S, int K){    int N = […]

#include using namespace std;  void findMostFrequent(int arr[], int N,                      int K){    int start = 0, end = 0;          sort(arr, arr + N);              int mostFreq = INT_MIN, sum = 0;          for (end = 0; end < N; end++) {                          sum = sum + arr[end];                  while (sum + K < arr[end] * (end - start + 1)) {                                      sum = sum - arr[start];                                      start++;        }                  mostFreq = max(mostFreq,                       end - […]

Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments.Examples:Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5 Output: 2 Explanation: Incrementing arr twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2. Incrementing […]

#include using namespace std;  int minSizeArr(int A[], int N, int K){            int leftTaken = N, rightTaken = N;          int leftSum = 0, rightSum = 0;          for (int left = -1; left < N; left++) {          if (left != -1)            leftSum += A[left];          rightSum = 0;                  for (int right = N - 1; right > left; right–) {              rightSum += A[right];              if (leftSum + rightSum == […]

Count number of substrings having at least K distinct characters Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters.Examples:Input: S = “abcca”, K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are:“abc”: […]