BackhardDynamic ProgrammingCredGoogle

Monotonic Threshold Span Resolver Solution

Problem Statement

You are given an array A of length $N$ representing a sequence of sensor readings. The goal is to partition the array into contiguous segments such that for every segment $[L, R]$, the difference between the maximum and minimum values in that segment does not exceed a given threshold $K$. The cost of a segment $[L, R]$ is defined as the length of the segment, i.e., $R - L + 1$. The total cost of a partition is the sum of the costs of all segments. Your task is to find the minimum total cost to partition the entire array under the given constraint.

Formally, let $dp[i]$ be the minimum cost to partition the prefix $A[0..i-1]$. The recurrence is: $dp[i] = \min_{j < i} { dp[j] + (i - j) }$, subject to the condition that $\max(A[j..i-1]) - \min(A[j..i-1]) \le K$.

Return the value of $dp[N]$. If no valid partition exists (which is impossible since single elements always satisfy the condition), return -1. However, since single elements always have max-min = 0 <= K, a valid partition always exists.

The naive DP runs in $O(N^2)$, which is too slow for large $N$. You must optimize this to $O(N \log N)$ or $O(N)$ using Divide and Conquer DP optimization, leveraging the monotonicity of the optimal split point.

Example 1
Input
A = [1, 2, 3, 4, 5], K = 2
Output
5

Explanation: The entire array [1,2,3,4,5] has max=5, min=1, diff=4 > 2, so it cannot be one segment. We must partition. Possible partitions: [1,2,3] and [4,5]. Cost = 3 + 2 = 5. Check [1,2,3]: max=3, min=1, diff=2 <= 2. Valid. [4,5]: max=5, min=4, diff=1 <= 2. Valid. Another option: [1,2], [3,4], [5]. Cost = 2+2+1=5. Same. Another: [1], [2,3,4], [5]. [2,3,4] diff=2<=2. Cost=1+3+1=5. Minimum is 5.

Example 2
Input
A = [10, 1, 10, 1, 10], K = 9
Output
5

Explanation: Check if whole array works: max=10, min=1, diff=9 <= 9. Valid. So one segment [10,1,10,1,10] with cost 5. This is the minimum possible since any partition into more segments would have total cost >= 5 (sum of lengths is always N). So answer is 5.

Example 3
Input
A = [5, 1, 5, 1, 5, 1], K = 3
Output
6

Explanation: Whole array: max=5, min=1, diff=4 > 3. Invalid. Try partitions. [5,1,5] diff=4>3 invalid. [5,1] diff=4>3 invalid. So each segment can have at most 2 elements if they are (5,1) or (1,5)? Wait, [5,1] diff=4>3. So no two adjacent elements can form a valid segment if they differ by 4. Thus, each segment must be of length 1. Cost = 6.

Example 4
Input
A = [1, 3, 2, 4, 3], K = 2
Output
5

Explanation: Whole array: max=4, min=1, diff=3 > 2. Invalid. Try [1,3,2]: max=3, min=1, diff=2 <= 2. Valid. [4,3]: max=4, min=3, diff=1 <= 2. Valid. Cost = 3+2=5. Try [1,3]: diff=2<=2. [2,4,3]: max=4, min=2, diff=2<=2. Cost=2+3=5. Try [1], [3,2,4,3]: max=4, min=2, diff=2<=2. Cost=1+4=5. Minimum is 5.

Constraints

  • 1 <= N <= 10^5
  • 1 <= A[i] <= 10^9
  • 0 <= K <= 10^9
  • Time limit: 2 seconds
  • Space limit: 256 MB
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Monotonic Threshold Span Resolver — Problem Statement & Solution Guide

Dynamic ProgrammingHardDivide and Conquer DP
TimeO(N)
|
SpaceO(N)

Problem Description

You are given an array A of length $N$ representing a sequence of sensor readings. The goal is to partition the array into contiguous segments such that for every segment $[L, R]$, the difference between the maximum and minimum values in that segment does not exceed a given threshold $K$. The cost of a segment $[L, R]$ is defined as the length of the segment, i.e., $R - L + 1$. The total cost of a partition is the sum of the costs of all segments. Your task is to find the minimum total cost to partition the entire array under the given constraint.

Formally, let $dp[i]$ be the minimum cost to partition the prefix $A[0..i-1]$. The recurrence is:

$dp[i] = \min_{j < i} \{ dp[j] + (i - j) \}$, subject to the condition that $\max(A[j..i-1]) - \min(A[j..i-1]) \le K$.

Return the value of $dp[N]$. If no valid partition exists (which is impossible since single elements always satisfy the condition), return -1. However, since single elements always have max-min = 0 <= K, a valid partition always exists.

The naive DP runs in $O(N^2)$, which is too slow for large $N$. You must optimize this to $O(N \log N)$ or $O(N)$ using Divide and Conquer DP optimization, leveraging the monotonicity of the optimal split point.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Threshold Span Resolver"

hard

WHY DOES IT MATTER?

This pattern is essential for solving problems that involve partitioning arrays under specific constraints, especially when the constraints are based on range properties like max-min differences. It combines dynamic programming with efficient data structures to achieve optimal performance.

OPTIMIZATION CHALLENGE

The key insight is recognizing that the valid starting indices $L$ for each ending index $R$ form a contiguous range. This allows the use of a sliding window technique to maintain the valid range, reducing the time complexity from $O(N^2)$ to $O(N)$.

REAL-WORLD CONNECTION

This pattern is analogous to load balancing in distributed systems, where tasks are partitioned into segments such that the load difference between any two segments does not exceed a threshold. Efficient partitioning ensures balanced resource utilization and prevents bottlenecks.

In interviews, clearly articulate the transition from the naive approach to the optimized one. Emphasize the use of deques for maintaining max and min values, and explain how the sliding window technique leverages the monotonicity of the valid range.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem of partitioning an array into contiguous segments where the difference between the maximum and minimum values does not exceed a threshold $K$ is a classic application of dynamic programming combined with sliding window techniques. A naive approach would involve checking all possible partitions, which results in an exponential time complexity of $O(2^N)$, making it infeasible for large $N$. The key insight is that for any ending index $R$, the valid starting indices $L$ form a contiguous range $[L_{min}, R]$. This property allows us to use a two-pointer or sliding window approach to maintain the valid range of $L$ for each $R$.

Interview Questions on This Problem

Q1How would you optimize the solution to handle large input sizes efficiently?

Use a sliding window technique to maintain the valid range of starting indices $L$ for each ending index $R$. This reduces the time complexity from $O(N^2)$ to $O(N)$ by leveraging the monotonicity of the valid range.

Q2What data structures would you use to efficiently track the maximum and minimum values in the current window?

Use two deques (double-ended queues) to maintain the maximum and minimum values in the current window. This allows for $O(1)$ amortized time complexity for both insertion and deletion operations.

Q3How would you handle edge cases such as an empty array or a single-element array?

For an empty array, return 0 as the total cost. For a single-element array, the cost is 1 since the segment is valid and has a length of 1.

Examples

Example 1

Input

A = [1, 2, 3, 4, 5], K = 2

Output

5

Explanation: The entire array [1,2,3,4,5] has max=5, min=1, diff=4 > 2, so it cannot be one segment. We must partition. Possible partitions: [1,2,3] and [4,5]. Cost = 3 + 2 = 5. Check [1,2,3]: max=3, min=1, diff=2 <= 2. Valid. [4,5]: max=5, min=4, diff=1 <= 2. Valid. Another option: [1,2], [3,4], [5]. Cost = 2+2+1=5. Same. Another: [1], [2,3,4], [5]. [2,3,4] diff=2<=2. Cost=1+3+1=5. Minimum is 5.

Example 2

Input

A = [10, 1, 10, 1, 10], K = 9

Output

5

Explanation: Check if whole array works: max=10, min=1, diff=9 <= 9. Valid. So one segment [10,1,10,1,10] with cost 5. This is the minimum possible since any partition into more segments would have total cost >= 5 (sum of lengths is always N). So answer is 5.

Example 3

Input

A = [5, 1, 5, 1, 5, 1], K = 3

Output

6

Explanation: Whole array: max=5, min=1, diff=4 > 3. Invalid. Try partitions. [5,1,5] diff=4>3 invalid. [5,1] diff=4>3 invalid. So each segment can have at most 2 elements if they are (5,1) or (1,5)? Wait, [5,1] diff=4>3. So no two adjacent elements can form a valid segment if they differ by 4. Thus, each segment must be of length 1. Cost = 6.

Example 4

Input

A = [1, 3, 2, 4, 3], K = 2

Output

5

Explanation: Whole array: max=4, min=1, diff=3 > 2. Invalid. Try [1,3,2]: max=3, min=1, diff=2 <= 2. Valid. [4,3]: max=4, min=3, diff=1 <= 2. Valid. Cost = 3+2=5. Try [1,3]: diff=2<=2. [2,4,3]: max=4, min=2, diff=2<=2. Cost=2+3=5. Try [1], [3,2,4,3]: max=4, min=2, diff=2<=2. Cost=1+4=5. Minimum is 5.

Constraints

  • 1 <= N <= 10^5
  • 1 <= A[i] <= 10^9
  • 0 <= K <= 10^9
  • Time limit: 2 seconds
  • Space limit: 256 MB

Optimal Approach & Strategy

The optimized approach uses dynamic programming with a sliding window technique. For each ending index $R$, we maintain the valid range of starting indices $L$ using two deques to track the maximum and minimum values. This reduces the time complexity to $O(N)$.

Brute Force Approach

The brute force approach involves checking all possible partitions of the array, which results in an exponential time complexity of $O(2^N)$. For each partition, we calculate the cost and keep track of the minimum total cost.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   if (nums.length <= 1) return nums.reduce((a, b) => a + b, 0);
   const mid = Math.floor(nums.length / 2);
   const leftSum = solution(nums.slice(0, mid));
   const rightSum = solution(nums.slice(mid));
   return leftSum + rightSum;
}

Asked in Top Tech Interviews

CredGoogle

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.