3578. Count Partitions With Max-Min Difference at Most K
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Count Partitions With Max-Min Difference at Most K (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Binary Search pattern in coding interviews. Sliding window; count partitions ending at each index where max-min ≤ k.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sliding window; count partitions ending at each index where max-min ≤ k.
Related patterns: Array, Binary Search, Dynamic Programming
3578.cs
C#
// Approach: Sliding window; count partitions ending at each index where max-min ≤ k.
// Time: O(n) Space: O(n)
public class Solution
{
public int CountPartitions(int[] nums, int k)
{
const int MOD = 1000000007;
LinkedList<int> maxDq = new LinkedList<int>();
LinkedList<int> minDq = new LinkedList<int>();
int n = nums.Length;
int[] dp = new int[n + 1];
dp[0] = 1;
int left = 0, suffix = 0;
for (int right = 0; right < n; right++)
{
suffix = (suffix + dp[right]) % MOD;
while (maxDq.Count > 0 && nums[maxDq.Last.Value] <= nums[right])
maxDq.RemoveLast();
maxDq.AddLast(right);
while (minDq.Count > 0 && nums[minDq.Last.Value] >= nums[right])
minDq.RemoveLast();
minDq.AddLast(right);
while (nums[maxDq.First.Value] - nums[minDq.First.Value] > k)
{
if (minDq.First.Value == left)
minDq.RemoveFirst();
if (maxDq.First.Value == left)
maxDq.RemoveFirst();
suffix = (suffix - dp[left] + MOD) % MOD;
left++;
}
dp[right + 1] = suffix;
}
return dp[n];
}
}Was this solution helpful?
Related Problems
- 1493. Longest Subarray of 1's After Deleting One Element(Medium)
- 1671. Minimum Number of Removals to Make Mountain Array(Hard)
- 1751. Maximum Number of Events That Can Be Attended II(Unknown)
- 2008. Maximum Earnings From Taxi(Unknown)
- 2009. Minimum Number of Operations to Make Array Continuous(Unknown)
- 2054. Two Best Non-Overlapping Events(Unknown)