Skip to content

Commit b0f8195

Browse files
committed
Sync LeetCode submission Runtime - 127 ms (37.28%), Memory - 30.6 MB (31.97%)
1 parent 88c3ff0 commit b0f8195

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<p>The <strong>score</strong> of an array is defined as the <strong>product</strong> of its sum and its length.</p>
2+
3+
<ul>
4+
<li>For example, the score of <code>[1, 2, 3, 4, 5]</code> is <code>(1 + 2 + 3 + 4 + 5) * 5 = 75</code>.</li>
5+
</ul>
6+
7+
<p>Given a positive integer array <code>nums</code> and an integer <code>k</code>, return <em>the <strong>number of non-empty subarrays</strong> of</em> <code>nums</code> <em>whose score is <strong>strictly less</strong> than</em> <code>k</code>.</p>
8+
9+
<p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [2,1,4,3,5], k = 10
16+
<strong>Output:</strong> 6
17+
<strong>Explanation:</strong>
18+
The 6 subarrays having scores less than 10 are:
19+
- [2] with score 2 * 1 = 2.
20+
- [1] with score 1 * 1 = 1.
21+
- [4] with score 4 * 1 = 4.
22+
- [3] with score 3 * 1 = 3.
23+
- [5] with score 5 * 1 = 5.
24+
- [2,1] with score (2 + 1) * 2 = 6.
25+
Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.</pre>
26+
27+
<p><strong class="example">Example 2:</strong></p>
28+
29+
<pre>
30+
<strong>Input:</strong> nums = [1,1,1], k = 5
31+
<strong>Output:</strong> 5
32+
<strong>Explanation:</strong>
33+
Every subarray except [1,1,1] has a score less than 5.
34+
[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.
35+
Thus, there are 5 subarrays having scores less than 5.
36+
</pre>
37+
38+
<p>&nbsp;</p>
39+
<p><strong>Constraints:</strong></p>
40+
41+
<ul>
42+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
43+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
44+
<li><code>1 &lt;= k &lt;= 10<sup>15</sup></code></li>
45+
</ul>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Approach: 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+
n = len(nums)
9+
res, total = 0, 0
10+
i = 0
11+
12+
for j in range(n):
13+
total += nums[j]
14+
while i <= j and total * (j - i + 1) >= k:
15+
total -= nums[i]
16+
i += 1
17+
res += j - i + 1
18+
19+
return res

0 commit comments

Comments
 (0)