Maximum Value in a Constrained Sequence
You want to build an integer array a of length n that satisfies the following rules:
- a[0] = 0.
- All elements must be non-negative (a[i] >= 0).
- The absolute difference between adjacent elements cannot exceed diff[i]. That is, abs(a[i] - a[i+1]) <= diff[i].
- You are given a 2D array restrictions where each element is formatted as [index, maxVal]. This enforces a hard upper limit, meaning a[index] <= maxVal. (Note: The value at the index does not have to be exactly equal to maxVal; it just cannot exceed it).
Your task is to return the absolute maximum value you can possibly place anywhere in this sequence without breaking any rules.
Example 1:
Input: n = 5, restrictions = [[3, 2]], diff = [2, 2, 2, 2]
Output:4
Explanation: One possible optimal sequence is a = [0, 2, 4, 2, 4]. Notice that a[3] is exactly at its restriction limit of 2, which happens to be optimal for this specific case, but remember the rule only requires a[3] <= 2. The maximum value in the array is 4.
Example 2:
Input:n = 4, restrictions = [[3, 0]], diff = [5, 5, 5]
Output:5
Explanation: The optimal sequence is a = [0, 5, 5, 0]. You might think a[2] could be 10 (since a[1] can be 5 and diff[1] = 5). However, restrictions forces a[3] <= 0 (so a[3] = 0). Because diff[2] = 5, a[2] cannot exceed a[3] + 5 = 5. Thus, a[2] is limited to 5 due to the backward difference constraint.
Now Your Turn!
Pick the correct output for the given inputInput: n = 6, restrictions = [[4, 2]], diff = [3, 1, 1, 1, 3]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 <= n <= 105
- 1 <= restrictions.length <= n - 1
- restrictions[i].length == 2
- restrictions[i] = [idx, maxVal]
- 1 <= idx < n
- 1 <= maxVal <= 106
- diff.length == n - 1
- 1 <= diff[i] <= 10
- The values of restrictions[i][0] are unique.