diff --git a/3578. Count Partitions With Max-Min Difference at Most K b/3578. Count Partitions With Max-Min Difference at Most K new file mode 100644 index 0000000..e864142 --- /dev/null +++ b/3578. Count Partitions With Max-Min Difference at Most K @@ -0,0 +1,32 @@ +class Solution { +public: + int countPartitions(vector& nums, int k) { + int n = nums.size(); + const int MOD = 1'000'000'007; + + vector dp(n+1,0); + dp[0] = 1; + + deque mx, mn; + int l = 0; + long long sum = 0; + + for(int r=0; r= nums[r]) mn.pop_back(); + mx.push_back(r); + mn.push_back(r); + + while(nums[mx.front()] - nums[mn.front()] > k){ + if(mx.front() == l) mx.pop_front(); + if(mn.front() == l) mn.pop_front(); + sum = (sum - dp[l] + MOD) % MOD; + l++; + } + + sum = (sum + dp[r]) % MOD; + dp[r+1] = sum; + } + return dp[n]; + } +};