Skip to content

Commit 677372d

Browse files
committed
Sync LeetCode submission Runtime - 70 ms (83.51%), Memory - 29.5 MB (77.76%)
1 parent 9f23784 commit 677372d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p>
2+
3+
<p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p>
4+
5+
<p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [1,3,2,3,3], k = 2
12+
<strong>Output:</strong> 6
13+
<strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [1,4,2,1], k = 3
20+
<strong>Output:</strong> 0
21+
<strong>Explanation:</strong> No subarray contains the element 4 at least 3 times.
22+
</pre>
23+
24+
<p>&nbsp;</p>
25+
<p><strong>Constraints:</strong></p>
26+
27+
<ul>
28+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
29+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
30+
<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
31+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach 1: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def countSubarrays(self, nums: List[int], k: int) -> int:
8+
max_elem = max(nums)
9+
ans = start = max_elem_in_window = 0
10+
11+
for end in range(len(nums)):
12+
if nums[end] == max_elem:
13+
max_elem_in_window += 1
14+
while max_elem_in_window == k:
15+
if nums[start] == max_elem:
16+
max_elem_in_window -= 1
17+
start += 1
18+
ans += start
19+
20+
return ans
21+

0 commit comments

Comments
 (0)