#3578

Count Partitions With Max-Min Difference at Most K

Medium
ArrayDynamic ProgrammingQueueSliding WindowPrefix SumMonotonic QueueHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use dynamic programming to efficiently count valid partitions by maintaining a sliding window of valid segments.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize dp array where dp[i] is the count of partitions ending at index i.
  2. 2Step 2: Use two pointers to maintain a window where the max-min difference is at most k.
  3. 3Step 3: Update dp[i] based on valid partitions from previous indices.
solution.py12 lines
1def countPartitions(nums, k):
2    n = len(nums)
3    dp = [0] * n
4    dp[0] = 1
5    total = 1
6    left = 0
7    for right in range(n):
8        while nums[right] - nums[left] > k:
9            left += 1
10        total = (total + dp[left - 1]) % (10**9 + 7)
11        dp[right] = total
12    return total

Complexity note: The time complexity is O(n) as we traverse the array once with two pointers, making it efficient.

  • 1Dynamic programming allows us to build solutions incrementally.
  • 2Using two pointers helps maintain valid segments efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.