Let n=R−L+1.
Consider sums made by choosing exactly k values. Their minimum and maximum are
lok=kL+2k(k−1),hi
When k distinct values are chosen from consecutive integers, every integer between these two bounds is attainable. Thus the sums form the integer interval Ik=[lok.
Both endpoints increase with k. Therefore, the union size equals the sum of all interval lengths minus the overlaps of consecutive intervals.
The length of Ik is
hik−lok+1=k(n−
The sum of all interval lengths is
k=1∑n(k(n−k)+
The overlap length of Ik and Ik+1 is
max(0,hik−lok
It is positive exactly when k(n−1−k)≥L.
The expression k(n−1−k) increases for k=1,2,…,⌊(n. Binary search for the smallest satisfying value . By symmetry, all satisfying indices are
a≤k≤n−1−a.
If no such value exists, the overlap sum is zero.
Let b=n−1−a. The total overlap to subtract is
k=a∑b
This is evaluated in O(1) using the standard formulas for ∑k and ∑k2.
All arithmetic for the answer is performed modulo 109+7. Use 128-bit integers for products in the binary-search comparisons.
The time complexity per test case is O(log(R−L+1)), and the additional space complexity is O(1).
Solution written by GPT6