The key is that the difference between consecutive elements in the copy array must match the difference in the original array. This means the entire copy array is determined by its first element. We need to find all possible values for copy[0] such that, after propagating the differences, every copy[i] stays within its bounds.
classSolution {
public:int numberOfArrays(vector<int>& original, vector<vector<int>>& bounds) {
int n = original.size();
longlong l = bounds[0][0], r = bounds[0][1];
for (int i =0; i < n; ++i) {
longlong diff = original[i] - original[0];
l = max(l, (longlong)bounds[i][0] - diff);
r = min(r, (longlong)bounds[i][1] - diff);
}
returnmax(0LL, r - l +1);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcnumberOfArrays(original []int, bounds [][]int) int {
n:= len(original)
l, r:=bounds[0][0], bounds[0][1]
fori:=0; i < n; i++ {
diff:=original[i] -original[0]
l = max(l, bounds[i][0]-diff)
r = min(r, bounds[i][1]-diff)
}
ifr < l {
return0 }
returnr-l+1}
func max(a, bint) int { ifa > b { returna }; returnb }
func min(a, bint) int { ifa < b { returna }; returnb }
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintnumberOfArrays(int[] original, int[][] bounds) {
int n = original.length;
long l = bounds[0][0], r = bounds[0][1];
for (int i = 0; i < n; i++) {
long diff = original[i]- original[0];
l = Math.max(l, bounds[i][0]- diff);
r = Math.min(r, bounds[i][1]- diff);
}
return (int)Math.max(0, r - l + 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funnumberOfArrays(original: IntArray, bounds: Array<IntArray>): Int {
val n = original.size
var l = bounds[0][0].toLong()
var r = bounds[0][1].toLong()
for (i in0 until n) {
val diff = original[i] - original[0]
l = maxOf(l, bounds[i][0] - diff.toLong())
r = minOf(r, bounds[i][1] - diff.toLong())
}
returnif (r < l) 0else (r - l + 1).toInt()
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defnumberOfArrays(self, original: list[int], bounds: list[list[int]]) -> int:
n = len(original)
l = bounds[0][0]
r = bounds[0][1]
for i in range(n):
diff = original[i] - original[0]
l = max(l, bounds[i][0] - diff)
r = min(r, bounds[i][1] - diff)
return max(0, r - l +1)
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnnumber_of_arrays(original: Vec<i32>, bounds: Vec<Vec<i32>>) -> i32 {
let n = original.len();
letmut l = bounds[0][0] asi64;
letmut r = bounds[0][1] asi64;
for i in0..n {
let diff = (original[i] - original[0]) asi64;
l = l.max(bounds[i][0] asi64- diff);
r = r.min(bounds[i][1] asi64- diff);
}
if r < l { 0 } else { (r - l +1) asi32 }
}
}