Skip to content
Discussion options

You must be logged in to vote

We need to count the number of ways to partition an array into contiguous segments where each segment's (max - min) ≤ k.
We need to count partitions where for each segment:

  • max(segment) - min(segment) ≤ k

This is a dynamic programming problem where:

  • dp[i] = number of valid partitions ending at index i
  • The transition is: dp[i] = sum(dp[j-1]) for all j ≤ i where segment [j, i] is valid

Approach

We can solve this using:

  1. Dynamic Programming to count ways
  2. Sliding Window to find valid segments
  3. Two Monotonic Queues to track min and max in current window
  4. Prefix Sum to efficiently compute sums of dp values

Key Insight

For position i, we need to find the leftmost index left such that all segm…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Dec 6, 2025
Maintainer Author

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Dec 6, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants