Skip to content

Commit d49016d

Browse files
authored
Create 3578. Count Partitions With Max-Min Difference at Most K (#951)
2 parents f0ff9fe + 0f693fc commit d49016d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
int countPartitions(vector<int>& nums, int k) {
4+
int n = nums.size();
5+
const int MOD = 1'000'000'007;
6+
7+
vector<long long> dp(n+1,0);
8+
dp[0] = 1;
9+
10+
deque<int> mx, mn;
11+
int l = 0;
12+
long long sum = 0;
13+
14+
for(int r=0; r<n; r++){
15+
while(!mx.empty() && nums[mx.back()] <= nums[r]) mx.pop_back();
16+
while(!mn.empty() && nums[mn.back()] >= nums[r]) mn.pop_back();
17+
mx.push_back(r);
18+
mn.push_back(r);
19+
20+
while(nums[mx.front()] - nums[mn.front()] > k){
21+
if(mx.front() == l) mx.pop_front();
22+
if(mn.front() == l) mn.pop_front();
23+
sum = (sum - dp[l] + MOD) % MOD;
24+
l++;
25+
}
26+
27+
sum = (sum + dp[r]) % MOD;
28+
dp[r+1] = sum;
29+
}
30+
return dp[n];
31+
}
32+
};

0 commit comments

Comments
 (0)