思路
对于每种隐藏数组,一旦确定开头,后续数组序列都是确定的,问题转化为lower到upper间的每种情况中,有多少是满足条件的;
而条件的限制是全在范围内,因此累加diff数组,记录最低会减多少,最高会加多少,如果开头加上这个最大变化幅度在范围内就是可行答案;
会爆int,所以要用long long
代码
class Solution {
public:
int numberOfArrays(vector<int>& diff, int lower, int upper) {
long long small = 1e6, big = -1e6;
int n = diff.size();
long long start = 0;
for(int i = 0; i < n; i++) {
start += diff[i];
small = min(start, small);
big = max(start, big);
}
int ans = 0;
for(long long i = lower; i <= upper; i++) {
if(i + small >= lower && i + big <= upper) ans++;
}
return ans;
}
};