bool isPossible(int mid, int k, vector<int> &stalls) {
int count = 1;
int lastPos = stalls[0];
for(int i=1; i < stalls.size(); i++) {
if(stalls[i] - lastPos >= mid) {
count++;
lastPos = stalls[i];
if(count == k) {
return true;
}
}
}
return false;
}
int aggressiveCows(vector<int> &stalls, int k) {
// Write your code here
sort(stalls.begin(), stalls.end());
int low = 1;
int high = stalls.back() - stalls.front();
int res = 0;
while(low <= high) {
int mid = low + (high - low) / 2;
if(isPossible(mid, k, stalls)) {
res = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return res;
}
Tag: gfg
GFG : Maximum MEX from all subarrays of length K
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum MEX from all subarray of length K. The MEX is the smallest positive integer that is not present in the array. Solution :
GFG : Count distinct elements in every window
Problem : Given an array of integers and a number K. Find the count of distinct elements in every window of size K in the array. Solution:
#54 Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 Solution : Complete code: