Count Subarrays Where Max Element Appears at Least K Times
Count the subarrays in which the largest value of the whole array appears at least k times.
Given an array of positive integers numskk
Example 1
Output: 6
Explanation: the subarrays are [1, 3, 2, 3], [1, 3, 2, 3, 3], [3, 2, 3], [3, 2, 3, 3], [2, 3, 3] and [3, 3].
Example 2
Output: 0
Explanation: the largest value, 4, appears only once, so no subarray can hold it three times.
The Idea
Think of [1, 3, 2, 3, 3]
Only one value matters here: the largest one, 3. The 1 and the 2 never decide anything; they only make a subarray longer. The array has 15 subarrays, and six of them hold two or more 3s. Checking 15 is easy, but an array of 100,000 numbers has about 5 billion subarrays. How can we count the good ones without looking at each?
Fix where the subarray ends and look at its possible starts. Take the subarrays that end at index 3, the second 3. Starting at index 3 gives [3][2, 3][3, 2, 3][1, 3, 2, 3]
Moving the start to the left only adds numbers, so the count of 3s can grow but never shrink. That means the good starts always form a block at the front: index 0 up to some point, and nothing after it. To count them, we only need to know where that block ends.
Look at the picture below. The blue box is a window: the numbers from a start position leftrightleft
In the row labelled right = 3[2, 3]left = 2right = 4left = 4
The ends at index 0, 1 and 2 add nothing, because [1, 3, 2]rightleft
A window whose two edges only ever move to the right is called a sliding window. Here it lets us count whole blocks of subarrays in one step, instead of listing them.
Solution Approach
Turning that idea into code means settling four things: how to find the largest value, how to count the subarrays for each end, how to move the window's left edge, and which type can hold the answer.
Finding the largest value
Which value are we counting? The largest value of the whole array, not the largest of each subarray. In Example 2 we count 4s, even when looking at [2, 1]max
Counting by the end of the subarray
Why not check every subarray? The simple way picks each start with one loop, and inside it a second loop extends the end one step at a time while counting copies of max
Instead, one loop moves the end rightleft - 1left
Moving the left edge
When does leftcountmaxleftrightrightmaxcountkleftk - 1
At that point the window starting at leftleft - 1kleftleft
Holding the answer
How large can the answer get? If all n numbers are equal and kintlong
Java Solution
The method countSubarrays
- First, find the largest value,
, with one loop overmax that starts fromnums .nums[0] - Set up the window:
starts at 0,left (the copies ofcount in the window) starts at 0, and the answermax , aresult , starts at 0.long - A second loop moves
from the first index to the last. Whenright equalsnums[right] , add one tomax .count - Inside that loop, a
loop runs as long aswhile equalscount . Ifk isnums[left] , take one offmax ; either way, movecount one place forward.left - Add
toleft , which counts the starts 0 toresult for thisleft - 1 .right - When the loop over
is done, returnright .result
The maink = 2k = 1k = 1
import java.util.Arrays;
public class CountSubarraysWhereMaxAppearsKTimes {
public static long countSubarrays(int[] nums, int k) {
int max = nums[0];
for (int x : nums) {
max = Math.max(max, x);
}
long result = 0;
int left = 0;
int count = 0; // copies of max in nums[left..right]
for (int right = 0; right < nums.length; right++) {
if (nums[right] == max) {
count++;
}
while (count == k) { // shrink until the window has k - 1 copies
if (nums[left] == max) {
count--;
}
left++;
}
result += left; // starts 0 .. left-1 all give >= k copies
}
return result;
}
public static void main(String[] args) {
System.out.println(countSubarrays(new int[] {1, 3, 2, 3, 3}, 2));
System.out.println(countSubarrays(new int[] {1, 4, 2, 1}, 3));
System.out.println(countSubarrays(new int[] {5, 5, 5}, 2));
System.out.println(countSubarrays(new int[] {7}, 1));
int[] same = new int[100000];
Arrays.fill(same, 9);
System.out.println(countSubarrays(same, 1));
}
}
Running it prints:
6
0
3
1
5000050000
Example 1 gives 6, the 2 + 4 from the picture, and Example 2 gives 0 because count[5, 5, 5]k = 2[5, 5][5, 5][5, 5, 5]
The single number 7 with k = 1intlongresult
Complexity
The work is one pass to find max
- Time: O(n), because the first loop reads each of the n numbers once,
visits each index once, andright never moves back, so all theleft loops together move it at most n times.while - Space: O(1), because the method keeps only
,max ,left ,right andcount , with no extra array or map.result
The same step of adding all the starts before left