|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold |
| 5 | + * |
| 6 | + * Given an array of integers arr and two integers k and threshold. |
| 7 | + * Return the number of sub-arrays of size k and average greater than or equal to threshold. |
| 8 | + * |
| 9 | + * Example 1: |
| 10 | + * Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 |
| 11 | + * Output: 3 |
| 12 | + * Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold). |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * Input: arr = [1,1,1,1,1], k = 1, threshold = 0 |
| 16 | + * Output: 5 |
| 17 | + * |
| 18 | + * Example 3: |
| 19 | + * Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 |
| 20 | + * Output: 6 |
| 21 | + * Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers. |
| 22 | + * |
| 23 | + * Example 4: |
| 24 | + * Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7 |
| 25 | + * Output: 1 |
| 26 | + * |
| 27 | + * Example 5: |
| 28 | + * Input: arr = [4,4,4,4], k = 4, threshold = 1 |
| 29 | + * Output: 1 |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * 1 <= arr.length <= 10^5 |
| 33 | + * 1 <= arr[i] <= 10^4 |
| 34 | + * 1 <= k <= arr.length |
| 35 | + * 0 <= threshold <= 10^4 |
| 36 | + * */ |
| 37 | +public class _1343 { |
| 38 | + public static class Solution1 { |
| 39 | + public int numOfSubarrays(int[] arr, int k, int threshold) { |
| 40 | + int sum = 0; |
| 41 | + for (int i = 0; i < k - 1; i++) { |
| 42 | + sum += arr[i]; |
| 43 | + } |
| 44 | + int count = 0; |
| 45 | + for (int i = k - 1; i < arr.length; i++) { |
| 46 | + sum += arr[i]; |
| 47 | + if (i - k >= 0) { |
| 48 | + sum -= arr[i - k]; |
| 49 | + } |
| 50 | + if (sum / k >= threshold) { |
| 51 | + count++; |
| 52 | + } |
| 53 | + } |
| 54 | + return count; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments