Technique
Contribution Technique (sum over all subarrays/pairs)
Instead of enumerating all subarrays/pairs, compute how many of them each element contributes to and sum value x count.
0/13 solved
Recognise it
The signal
sum over all subarrays/subsequences/pairs of some function (min, max, range, XOR bit)
1Brute force
Enumerate every subarray/pair and evaluate the function.
2The observation
Enumerating O(n2) objects: swap the order of summation and count per element.
3Why it works
Each object is attributed to exactly one element (tie-break strict on one side, non-strict on the other).
Reach for it when
- +answer is a big sum modulo M
Not when
- ×function does not decompose per element or per bit
Practice
- Sum of Subarray MinimumsCitadel, Goldman SachsMedium
- Sum of Subarray RangesMedium
- Password Strength (Sum of Distinct Chars over Substrings)AmazonOAMedium
- Distinct Values SumCSESMedium
- Maximum Distributed TreeCodeforces1800
- Range AND ChallengeRubrikOAMedium
- Moving RobotsCSESHard
- Inversion ProbabilityCSESHard
- Sum of Total Strength of WizardsHard
- Sum of Total Strength of WizardsAmazonOAHard
- All Manhattan DistancesCSESHard
- Transfer Speeds SumCSESHard
- Imbalance Value of a TreeCodeforces2400
Pitfalls
Misconceptions
- !double counting equal values
Go deeper3 combinations · resources
Combinations
Monotonic Stack+Contribution Technique (sum over all subarrays/pairs)
sum over all subarrays of min, max, or range
- Monotonic Stack:
- finds each element's span where it is min/max
- Contribution Technique (sum over all subarrays/pairs):
- sums value x number of subarrays
Probability & Expected-Value DP (linearity of expectation)+Contribution Technique (sum over all subarrays/pairs)
expected number of inversions / empty squares / matches
- Probability & Expected-Value DP (linearity of expectation):
- linearity: sum the indicator probabilities
- Contribution Technique (sum over all subarrays/pairs):
- split the total into per-pair or per-square indicators
Monotonic Stack+Contribution Technique (sum over all subarrays/pairs)+Prefix Sum
sum over all subarrays of min * sum (or similar products)
- Monotonic Stack:
- previous/next smaller bounds for each element
- Contribution Technique (sum over all subarrays/pairs):
- each element is the min of all subarrays inside its bounds
- Prefix Sum:
- prefix sums of prefix sums give those subarrays' total sum in O(1)