-
Notifications
You must be signed in to change notification settings - Fork 5
/
CountSubarraysWithScoreLessThanK.java
52 lines (50 loc) · 1.48 KB
/
CountSubarraysWithScoreLessThanK.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*https://leetcode.com/problems/count-subarrays-with-score-less-than-k/*/
class Solution {
public long countSubarrays(int[] nums, long k) {
int n = nums.length;
long count = 0;
int start = 0, end = 0;
long sumTillNow = 0, lenTillNow = 0, scoreTillNow = 0;
while (end < n)
{
sumTillNow += nums[end];
lenTillNow += 1;
scoreTillNow += sumTillNow;
scoreTillNow += nums[end]*(lenTillNow-1);
while (scoreTillNow >= k)
{
sumTillNow -= nums[start];
lenTillNow -= 1;
scoreTillNow -= sumTillNow;
scoreTillNow -= nums[start++]*(lenTillNow+1);
}
if (scoreTillNow < k)
count += lenTillNow;
++end;
}
return count;
}
}
class Solution {
public long countSubarrays(int[] nums, long k) {
int n = nums.length;
long count = 0;
int start = 0, end = 0;
long sumTillNow = 0, lenTillNow = 0, scoreTillNow = 0;
while (end < n)
{
sumTillNow += nums[end];
++lenTillNow;
scoreTillNow = sumTillNow*lenTillNow;
while (scoreTillNow >= k)
{
sumTillNow -= nums[start++];
--lenTillNow;
scoreTillNow = sumTillNow*lenTillNow;
}
count += lenTillNow;
++end;
}
return count;
}
}